. Htaccess File Usage Overview
Various practical. htaccess code snippets are collected here. You can think of almost all the usage here.
Disclaimer: although these code snippets are directly copied to your.htaccess
Files are easy to use in most cases, but there are also a few situations that require you to modify some places. At your own risk.
Important: Apache 2.4 has incompatible modifications, especially in terms of access configuration control. For more information, see this updated document and this article.
Directory
- Refresh and redirect
- Force www
- Universal Method for forcing www
- Force non-www
- Enforce general non-www Methods
- Force HTTPS
- Force HTTPS to use proxy
- Force add end slash
- Remove the end slash
- Redirect to a page
- Directory alias
- Script alias
- Redirect the entire website
- Clean URL
- Security
- Deny all access
- Deny all access (excluded)
- Blocking crawlers/malicious access
- Protect hidden files and directories
- Protect Backup files and source code files
- Disable directory browsing
- Disable image leeching
- Disable image leeching (specified domain name)
- Password protection directory
- Password protection File
- Filter visitors by Referrer
- Prevent nesting by other webpages
- Performance
- Compressed file
- Set expiration header information
- Disable eTags
- Others
- Set PHP Variables
- Custom Error Pages
- Force download
- Download Blocking
- Run CORS font reference
- Auto UTF-8 Encode
- Switch PHP version
- Disable IE Compatibility View
- Support WebP image format
Refresh and redirect
Note: you must first install and enable the server.mod_rewrite
Module.
Force www
RewriteEngine onRewriteCond %{HTTP_HOST} ^example\.com [NC]RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]
Universal Method for forcing www
RewriteCond %{HTTP_HOST} !^$RewriteCond %{HTTP_HOST} !^www\. [NC]RewriteCond %{HTTPS}s ^on(s)|RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
This method can be used on any website. Source
Force non-www
Whether WWW is good or non-www is good, there is no final conclusion. If you prefer not to include www, you can use the following script:
RewriteEngine onRewriteCond %{HTTP_HOST} ^www\.example\.com [NC]RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]
Enforce general non-www Methods
RewriteEngine onRewriteCond %{HTTP_HOST} ^www\.RewriteCond %{HTTPS}s ^on(s)|offRewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L]
Force HTTPS
RewriteEngine onRewriteCond %{HTTPS} !onRewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}# Note: It's also recommended to enable HTTP Strict Transport Security (HSTS) # on your HTTPS website to help prevent man-in-the-middle attacks.# See https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security<IfModule mod_headers.c> Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"</IfModule>
Force HTTPS to use proxy
If you use a proxy, this method is useful to you.
RewriteCond %{HTTP:X-Forwarded-Proto} !httpsRewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
Force add end slash
RewriteCond %{REQUEST_URI} /+[^\.]+$RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]
Remove the end slash
RewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^(.*)/$ /$1 [R=301,L]
Redirect to a page
Redirect 301 /oldpage.html http://www.example.com/newpage.htmlRedirect 301 /oldpage2.html http://www.example.com/folder/
Source
Directory alias
RewriteEngine OnRewriteRule ^source-directory/(.*) target-directory/$1
Script alias
FallbackResource /index.fcgi
This example hasindex.fcgi
File in some directory, and any requests within that directory that fail to resolve a filename/directory will be sent toindex.fcgi
Script. It's good if you wantbaz.foo/some/cool/path
To be handledbaz.foo/index.fcgi
(Which also supports requestsbaz.foo
) While maintainingbaz.foo/css/style.css
And the like. Get access to the original path from the PATH_INFO environment variable, as exposed to your scripting environment.
RewriteEngine OnRewriteRule ^$ index.fcgi/ [QSA,L]RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^(.*)$ index.fcgi/$1 [QSA,L]
This is a less efficient version of the FallbackResource directive (because usingmod_rewrite
Is more complex than just handlingFallbackResource
Directive), but it's also more flexible.
Redirect the entire website
Redirect 301 / http://newsite.com/
This way does it with links intact. That iswww.oldsite.com/some/crazy/link.html
Will becomewww.newsite.com/some/crazy/link.html
. This is extremely helpful when you are just "moving" a site to a new domain. Source
Clean URL
This snippet lets you use "clean" URLs-those without a PHP extension, e.g.example.com/users
Insteadexample.com/users.php
.
RewriteEngine OnRewriteCond %{SCRIPT_FILENAME} !-dRewriteRule ^([^.]+)$ $1.php [NC,L]
Source
Security rejects all access
## Apache 2.2Deny from all## Apache 2.4# Require all denied
But wait, this will lock you out from your content as well! Thus introducing...
Deny all access (excluded)
## Apache 2.2Order deny,allowDeny from allAllow from xxx.xxx.xxx.xxx## Apache 2.4# Require all denied# Require ip xxx.xxx.xxx.xxx
xxx.xxx.xxx.xxx
Is your IP. if you replace the last three digits with 0/12 for example, this will specify a range of IPs within the same network, thus saving you the trouble to list all allowed IPs separately. source
Now of course there's a reversed version:
Blocking crawlers/malicious access
## Apache 2.2Order deny,allowAllow from allDeny from xxx.xxx.xxx.xxxDeny from xxx.xxx.xxx.xxy## Apache 2.4# Require all granted# Require not ip xxx.xxx.xxx.xxx# Require not ip xxx.xxx.xxx.xxy
Protect hidden files and directories
Hidden files and directories (those whose names start with a dot.
) Shoshould most, if not all, of the time be secured. For example:.htaccess
,.htpasswd
,.git
,.hg
...
RewriteCond %{SCRIPT_FILENAME} -d [OR]RewriteCond %{SCRIPT_FILENAME} -fRewriteRule "(^|/)\." - [F]
Alternatively, you can just raiseNot Found
Error, giving the attacker dude no clue:
RedirectMatch 404 /\..*$
Protect Backup files and source code files
These files may be left by some text/html editors (like Vi/Vim) and pose a great security danger if exposed to public.
<FilesMatch "(\.(bak|config|dist|fla|inc|ini|log|psd|sh|sql|swp)|~)$"> ## Apache 2.2 Order allow,deny Deny from all Satisfy All ## Apache 2.4 # Require all denied</FilesMatch>
Source
Disable directory browsing
Options All -Indexes
Disable image leeching
RewriteEngine on# Remove the following line if you want to block blank referrer tooRewriteCond %{HTTP_REFERER} !^$RewriteCond %{HTTP_REFERER} !^http(s)?://(.+\.)?example.com [NC]RewriteRule \.(jpg|jpeg|png|gif|bmp)$ - [NC,F,L]# If you want to display a "blocked" banner in place of the hotlinked image, # replace the above rule with:# RewriteRule \.(jpg|jpeg|png|gif|bmp) http://example.com/blocked.png [R,L]
Disable image leeching (specified domain name)
Sometimes you want to disable image leeching from some bad guys only.
RewriteEngine onRewriteCond %{HTTP_REFERER} ^http(s)?://(.+\.)?badsite\.com [NC,OR]RewriteCond %{HTTP_REFERER} ^http(s)?://(.+\.)?badsite2\.com [NC,OR]RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]# If you want to display a "blocked" banner in place of the hotlinked image, # replace the above rule with:# RewriteRule \.(jpg|jpeg|png|gif|bmp) http://example.com/blocked.png [R,L]
Password protection directory
First you need to create.htpasswd
File somewhere in the system:
htpasswd -c /home/fellowship/.htpasswd boromir
Then you can use it for authentication:
AuthType BasicAuthName "One does not simply"AuthUserFile /home/fellowship/.htpasswdRequire valid-user
Password protection File
AuthName "One still does not simply"AuthType BasicAuthUserFile /home/fellowship/.htpasswd<Files "one-ring.o">Require valid-user</Files><FilesMatch ^((one|two|three)-rings?\.o)$>Require valid-user</FilesMatch>
Filter visitors by Referrer
This denies access for all users who are coming from (referred by) a specific domain.
Source
RewriteEngine on# Options +FollowSymlinksRewriteCond %{HTTP_REFERER} somedomain\.com [NC,OR]RewriteCond %{HTTP_REFERER} anotherdomain\.comRewriteRule .* - [F]
Prevent nesting by other webpages
This prevents the website to be framed (I. e. put intoiframe
Tag), when still allows framing for a specific URI.
SetEnvIf Request_URI "/starry-night" allow_framing=trueHeader set X-Frame-Options SAMEORIGIN env=!allow_framing
Performance compressed file
<IfModule mod_deflate.c> # force compression for mangled headers .# http://developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping <IfModule mod_setenvif.c> <IfModule mod_headers.c> SetEnvIfNoCase ^ (Accept-EncodXng | X-cept-Encoding | X {15} | ~ {15} |-{15}) $ ^ (gzip | deflate) \ s *,? \ S *) + | [X ~ -] {} $ HAVE_Accept-Encoding RequestHeader append Accept-Encoding "gzip, deflate "env = HAVE_Accept-Encoding </IfModule> # Compress all output labeled with one of the following MIME-types # (for Apache versions below 2.3.7, you don't need to enable 'mod _ filter' # and can remove the '<IfModule mod_filter.c>' and '</IfModule> 'Lines # as 'addoutputfilterbytype' is still in core ctictives ). <IfModule mod_filter.c> AddOutputFilterByType DEFLATE application/atom + xml \ application/javascript \ application/json \ application/rss + xml \ application/vnd. ms-fontobject \ application/x-font-ttf \ application/x-web-app-manifest + json \ application/xhtml + xml \ application/xml \ font/opentype \ image/ svg + xml \ image/x-icon \ text/css \ text/html \ text/plain \ text/x-component \ text/xml </IfModule>
Source
Set expiration header information
Expires headersTell the browser whether they shocould request a specific file from the server or just grab it from the cache. It is advisable to set static content's expires headers to something far in the future.
If you don't control versioning with filename-based cache busting, consider lowering the cache time for resources like CSS and JS to something like 1 week. Source
<IfModule mod_expires.c> ExpiresActive on ExpiresDefault "access plus 1 month" # CSS ExpiresByType text/css "access plus 1 year" # Data interchange ExpiresByType application/json "access plus 0 seconds" ExpiresByType application/xml "access plus 0 seconds" ExpiresByType text/xml "access plus 0 seconds" # Favicon (cannot be renamed!) ExpiresByType image/x-icon "access plus 1 week" # HTML components (HTCs) ExpiresByType text/x-component "access plus 1 month" # HTML ExpiresByType text/html "access plus 0 seconds" # JavaScript ExpiresByType application/javascript "access plus 1 year" # Manifest files ExpiresByType application/x-web-app-manifest+json "access plus 0 seconds" ExpiresByType text/cache-manifest "access plus 0 seconds" # Media ExpiresByType audio/ogg "access plus 1 month" ExpiresByType image/gif "access plus 1 month" ExpiresByType image/jpeg "access plus 1 month" ExpiresByType image/png "access plus 1 month" ExpiresByType video/mp4 "access plus 1 month" ExpiresByType video/ogg "access plus 1 month" ExpiresByType video/webm "access plus 1 month" # Web feeds ExpiresByType application/atom+xml "access plus 1 hour" ExpiresByType application/rss+xml "access plus 1 hour" # Web fonts ExpiresByType application/font-woff2 "access plus 1 month" ExpiresByType application/font-woff "access plus 1 month" ExpiresByType application/vnd.ms-fontobject "access plus 1 month" ExpiresByType application/x-font-ttf "access plus 1 month" ExpiresByType font/opentype "access plus 1 month" ExpiresByType image/svg+xml "access plus 1 month"</IfModule>
Disable eTags
By removingETag
Header, you disable caches and browsers from being able to validate files, so they are forced to rely on yourCache-Control
AndExpires
Header. Source
<IfModule mod_headers.c> Header unset ETag</IfModule>FileETag None
Miscellaneous setting PHP Variables
php_value <key> <val># For example:php_value upload_max_filesize 50Mphp_value max_execution_time 240
Custom Error Pages
ErrorDocument 500 "Houston, we have a problem."ErrorDocument 401 http://error.example.com/mordor.htmlErrorDocument 404 /errors/halflife3.html
Force download
Sometimes you want to force the browser to download some content instead of displaying it.
<Files *.md> ForceType application/octet-stream Header set Content-Disposition attachment</Files>
Now there is a yang to this yin:
Download Blocking
Sometimes you want to force the browser to display some content instead of downloading it.
<FilesMatch "\.(tex|log|aux)$"> Header set Content-Type text/plain</FilesMatch>
Run CORS font reference
CDN-served webfonts might not work in Firefox or IE due to CORS. This snippet solves the problem.
<IfModule mod_headers.c> <FilesMatch "\.(eot|otf|ttc|ttf|woff|woff2)$"> Header set Access-Control-Allow-Origin "*" </FilesMatch></IfModule>
Source
Auto UTF-8 Encode
Your text content shocould always be UTF-8 encoded, no?
# Use UTF-8 encoding for anything served text/plain or text/htmladddefadefacharset UTF-8 # force UTF-8 for a number of file formatsAddCharset UTF-8. atom. css. js. json. rss. vtt. xml
Source
Switch PHP version
If you're on a shared host, chances are there are more than one version of PHP installed, and sometimes you want a specific version for your website. for example, Laravel requires PHP> = 5.4. the following snippet shoshould switch the PHP version for you.
AddHandler application/x-httpd-php55 .php# Alternatively, you can use AddTypeAddType application/x-httpd-php55 .php
Disable IE Compatibility View
Compatibility View in IE may affect how some websites are displayed. The following snippet shocould force IE to use the Edge Rendering Engine and disable the Compatibility View.
<IfModule mod_headers.c> BrowserMatch MSIE is-msie Header set X-UA-Compatible IE=edge env=is-msie</IfModule>
Support WebP image format
If WebP images are supported and an image with. webp extension and the same name is found at the same place as the jpg/png image that is going to be served, then the WebP image is served instead.
RewriteEngine OnRewriteCond %{HTTP_ACCEPT} image/webpRewriteCond %{DOCUMENT_ROOT}/$1.webp -fRewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1]
Source
This article permanently updates the link address: