21 useful. htaccess tips and tips

Source: Internet
Author: User
Tags set cookie website performance

The Apache Web server can operate on various information through the. htaccess file, which is the default name of a directory-level configuration file and allows decentralized Web server configuration management. It can be used to override the global configuration of the server. The purpose of this file is to allow access control configurations in a separate directory, such as password and content access. Below are 21 very useful. htaccess configuration tips and tips:

1. Customize the Index file of the Directory
1 DirectoryIndex index.html index.php index.htm

You can use the above configuration to change the default page of the directory. For example, if you put this script in the foo directory, the user will access/foo/index.html when requesting/foo /.

2. custom error page
ErrorDocument 404 errors/404.html

When a user reports an error when accessing the page, for example, the page cannot find the page you want to display a custom error page, you can do so. Or a dynamic page:

1 ErrorDocument 404 /psych/cgi-bin/error/error?404
3. Control the access file and directory levels

. Htaccess is often used to restrict and deny access to a certain file and directory. For example, we have a folder named des, which stores some scripts. We do not want users to directly access this folder, the following script can be used:

# no one gets in here!    deny from all

The preceding script rejects all access requests. You can also reject requests based on the IP address segment:

# no nasty crackers in here!    order deny,allow    deny from all    allow from 192.168.0.0/24    # this would do the same thing..    #allow from 192.168.0

These methods are generally handled through the firewall, but such adjustments are very convenient for servers in a production environment.

Sometimes you just want to disable access from an ip address:

1 # someone else giving the ruskies a bad name..    2 order allow,deny    3 deny from 83.222.23.219    4 allow from all
4. Modify Environment Variables

The environment variable contains some extended information about CGI on the server, which can be usedSetEnvAndUnSetEnvSet and cancel the settings.

SetEnv SITE_WEBMASTER "Jack Sprat"    SetEnv SITE_WEBMASTER_URI mailto:Jack.Sprat@characterology.com                UnSetEnv REMOTE_ADDR
301 redirection

If you want a page to jump to a new page:

Redirect 301 /old/file.html http://yourdomain.com/new/file.html

The following code redirects the entire path.

RedirectMatch 301 /blog(.*) http://yourdomain.com/$1
6. Implement cache policies through. htaccess

By setting static files cached in the browser, you can improve the website performance:

# year    <FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|swf|mp3|mp4)$">    Header set Cache-Control "public"    Header set Expires "Thu, 15 Apr 2010 20:00:00 GMT"    Header unset Last-Modified    </FilesMatch>    #2 hours    <FilesMatch "\.(html|htm|xml|txt|xsl)$">    Header set Cache-Control "max-age=7200, must-revalidate"    </FilesMatch>    <FilesMatch "\.(js|css)$">    SetOutputFilter DEFLATE    Header set Expires "Thu, 15 Apr 2010 20:00:00 GMT"    </FilesMatch>
7. Use GZIP to compress the output

Add the following code to. htaccess to compress all css, js, and html using the GZIP algorithm:

<IfModule mod_gzip.c>        mod_gzip_on       Yes        mod_gzip_dechunk  Yes        mod_gzip_item_include file      \.(html?|txt|css|js|php|pl)$        mod_gzip_item_include handler   ^cgi-script$        mod_gzip_item_include mime      ^text/.*        mod_gzip_item_include mime      ^application/x-javascript.*        mod_gzip_item_exclude mime      ^image/.*        mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*    </IfModule>

The premise of using the above Code is to enable the mod_gzip module. You can use the following script to determine whether the Web server provides mod_deflate support:

<Location>        SetOutputFilter DEFLATE          SetEnvIfNoCase Request_URI  \            \.(?:gif|jpe?g|png)$ no-gzip dont-vary        SetEnvIfNoCase Request_URI  \            \.(?:exe|t?gz|zip|gz2|sit|rar)$ no-gzip dont-vary    </Location>

If the Web server does not support mod_deflate, you can use the following method:

<FilesMatch "\.(txt|html|htm|php)">        php_value output_handler ob_gzhandler    </FilesMatch>
8. HTTPS access is required.

Use the following script to force the entire website to be accessed through https:

RewriteEngine On    RewriteCond %{HTTPS} !on    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
9. URL rewriting

For example? Id = 12 override to product-12.html

RewriteEngine on    RewriteRule ^product-([0-9]+)\.html$ product.php?id=$1

Add product. php? Id = 12 rewrite to product/ipod-nano/12.html

RewriteEngine on    RewriteRule ^product/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ product.php?id=$2

No URL from www TO www is redirected:

RewriteEngine On    RewriteCond %{HTTP_HOST} ^viralpatel\.net$    RewriteRule (.*) http://www.viralpatel.net/$1 [R=301,L]

 

Rewrite yoursite.com/user.php? Username = xyz to yoursite.com/xyz

RewriteEngine On    RewriteRule ^([a-zA-Z0-9_-]+)$ user.php?username=$1    RewriteRule ^([a-zA-Z0-9_-]+)/$ user.php?username=$1

 

 

Redirects a domain name to a new sub-folder in public_html.

RewriteEngine On    RewriteCond %{HTTP_HOST} ^test\.com$ [OR]    RewriteCond %{HTTP_HOST} ^www\.test\.com$    RewriteCond %{REQUEST_URI} !^/new/    RewriteRule (.*) /new/$1

10. Block listing directory files

Use the following code to prevent all objects in the List Directory:

Options -Indexes

Or

IndexIgnore *
11. Add a new MIME-Types

MIME-types depends on the file extension. unrecognized file extensions are transmitted as text data.

AddType application/x-endnote-connection enz    AddType application/x-endnote-filter enf    AddType application/x-spss-savefile sav
12. Anti-leech

You do not want other websites to reference static files such as images and css files on your website, that is, the legendary anti-leech. You can use the following script:

RewriteCond %{HTTP_REFERER} !^$    RewriteCond %{REQUEST_URI} !^/(wp-login.php|wp-admin/|wp-content/plugins/|wp-includes/).* [NC]    RewriteCond %{HTTP_REFERER} !^http://www.askapache.com.*$ [NC]    RewriteRule \.(ico|pdf|flv|jpg|jpeg|mp3|mpg|mp4|mov|wav|wmv|png|gif|swf|css|js)$ - [F,NS,L]
13. Specify the size limit of the uploaded file, applicable to PHP
php_value upload_max_filesize 20M    php_value post_max_size 20M    php_value max_execution_time 200    php_value max_input_time 200

In the preceding script, four parameters are used to set the File Upload limit. The first parameter is the file size, and the second parameter is the POST data size, the third is the transmission time (in seconds), and the last is the maximum time (in seconds) spent on parsing and uploading data)

14. Prohibit Script Execution
Options -ExecCGI    AddHandler cgi-script .php .pl .py .jsp .asp .htm .shtml .sh .cgi
15. Modify character sets and language Headers
AddDefaultCharset UTF-8    DefaultLanguage en-US
16. Set the server time zone (GMT)
SetEnv TZ America/Indianapolis
17. Force "File Save As" prompt
AddType application/octet-stream .avi .mpg .mov .pdf .xls .mp4
18. Protect a single file

Under normal circumstances,. htaccess can be used to restrict access to the entire directory, but it can also only restrict access to a file

 1 <Files quiz.html>     2 order deny,allow     3 deny from all     4 AuthType Basic     5 AuthName "Characterology Student Authcate"     6 AuthLDAP on     7 AuthLDAPServer ldap://directory.characterology.com/     8 AuthLDAPBase "ou=Student, o=Characterology University, c=au"     9 require valid-user    10 satisfy any    11 </Files>
19. Set Cookie

Set Cookie through environment variables

Header set Set-Cookie "language=%{lang}e; path=/;" env=lang

This code sends the Set-Cookie header to Set the Cookie value to the matching item in the second bracket based on the request setting Cookie.

RewriteEngine On    RewriteBase /    RewriteRule ^(.*)(de|es|fr|it|ja|ru|en)/$ - [co=lang:$2:.yourserver.com:7200:/]
20. Set custom Response Headers
Header set P3P "policyref=\"http://www.askapache.com/w3c/p3p.xml\""    Header set X-Pingback "http://www.askapache.com/xmlrpc.php"    Header set Content-Language "en-US"    Header set Vary "Accept-Encoding"
21. User-Agent is used to block requests
SetEnvIfNoCase ^User-Agent$ .*(craftbot|download|extract|stripper|sucker|ninja|clshttp|webspider|leacher|collector|grabber|webpictures) HTTP_SAFE_BADBOT    SetEnvIfNoCase ^User-Agent$ .*(libwww-perl|aesop_com_spiderman) HTTP_SAFE_BADBOT    Deny from env=HTTP_SAFE_BADBOT

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.