實用 .htaccess 用法大全

techug發表於2015-03-17

  這裡收集的是各種實用的 .htaccess 程式碼片段,你能想到的用法幾乎全在這裡。

  免責宣告: 雖然將這些程式碼片段直接拷貝到你的 .htaccess 檔案裡,絕大多數情況下都是好用的,但也有極個別情況需要你修改某些地方才行。風險自負。

  重要提示: Apache 2.4 有不相容的修改,特別是在訪問配置控制方面。詳細資訊請參考這篇更新文件以及這篇文章

 重新和重定向

  注意:首先需要伺服器安裝和啟用mod_rewrite模組。

  強制 www

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]

  強制 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]

  這種方法可以使用在任何網站中。 Source

  強制 non-www

  究竟是WWW好,還是non-www好,沒有定論,如果你喜歡不帶www的,可以使用下面的指令碼:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

  強制 non-www通用方法

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|off
RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$
RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L]

  強制 HTTPS

RewriteEngine on
RewriteCond %{HTTPS} !on
RewriteRule (.*) 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>

  強制 HTTPS 通過代理

  如果你使用了代理,這種方法對你很有用。

RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

  強制新增末尾斜槓

RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

  取掉末尾斜槓

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]

  重定向到一個頁面

Redirect 301 /oldpage.html http://www.example.com/newpage.html
Redirect 301 /oldpage2.html http://www.example.com/folder/

  Source

  目錄別名

RewriteEngine On
RewriteRule ^source-directory/(.*) target-directory/$1

  指令碼別名

FallbackResource /index.fcgi

  This example has an index.fcgi file in some directory, and any requests within that directory that fail to resolve a filename/directory will be sent to the index.fcgi script. It’s good if you want baz.foo/some/cool/path to be handled by baz.foo/index.fcgi (which also supports requests to baz.foo) while maintaining baz.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 On
RewriteRule ^$ index.fcgi/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L]

  This is a less efficient version of the FallbackResource directive (because using mod_rewrite is more complex than just handling the FallbackResource directive), but it’s also more flexible.

  重定向整個網站

Redirect 301 / http://newsite.com/

  This way does it with links intact. That is www.oldsite.com/some/crazy/link.html will become www.newsite.com/some/crazy/link.html. This is extremely helpful when you are just “moving” a site to a new domain. Source

  乾淨的URL

  This snippet lets you use “clean” URLs — those without a PHP extension, e.g. example.com/users instead of example.com/users.php.

RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]

  Source

 安全

  拒絕所有訪問

## Apache 2.2
Deny from all

## Apache 2.4
# Require all denied

  But wait, this will lock you out from your content as well! Thus introducing…

  拒絕所有訪問(排除部分)

## Apache 2.2
Order deny,allow
Deny from all
Allow 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:

  遮蔽爬蟲/惡意訪問

## Apache 2.2
Order deny,allow
Allow from all
Deny from xxx.xxx.xxx.xxx
Deny 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

  保護隱藏檔案和目錄

  Hidden files and directories (those whose names start with a dot .) should most, if not all, of the time be secured. For example: .htaccess, .htpasswd, .git, .hg…

RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule "(^|/)\." - [F]

  Alternatively, you can just raise a Not Found error, giving the attacker dude no clue:

RedirectMatch 404 /\..*$

  保護備份檔案和原始碼檔案

  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

  禁止目錄瀏覽

Options All -Indexes

  禁止圖片盜鏈

RewriteEngine on
# Remove the following line if you want to block blank referrer too
RewriteCond %{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]

  禁止圖片盜鏈(指定域名)

  Sometimes you want to 禁止圖片盜鏈 from some bad guys only.

RewriteEngine on
RewriteCond %{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]

  密碼保護目錄

  First you need to create a .htpasswd file somewhere in the system:

htpasswd -c /home/fellowship/.htpasswd boromir

  Then you can use it for authentication:

AuthType Basic
AuthName "One does not simply"
AuthUserFile /home/fellowship/.htpasswd
Require valid-user

  密碼保護檔案

AuthName "One still does not simply"
AuthType Basic
AuthUserFile /home/fellowship/.htpasswd

<Files "one-ring.o">
Require valid-user
</Files>

<FilesMatch ^((one|two|three)-rings?\.o)$>
Require valid-user
</FilesMatch>

  通過Referrer過濾訪客

  This denies access for all users who are coming from (referred by) a specific domain.
Source

RewriteEngine on
# Options +FollowSymlinks
RewriteCond %{HTTP_REFERER} somedomain\.com [NC,OR]
RewriteCond %{HTTP_REFERER} anotherdomain\.com
RewriteRule .* - [F]

  防止被別的網頁巢狀

  This prevents the website to be framed (i.e. put into an iframe tag), when still allows framing for a specific URI.

SetEnvIf Request_URI "/starry-night" allow_framing=true
Header set X-Frame-Options SAMEORIGIN env=!allow_framing

 效能

  壓縮檔案

<IfModule mod_deflate.c>

    # 強制 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~-]{4,13}$ HAVE_Accept-Encoding
            RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
        </IfModule>
    </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 the core directives).
    <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>

</IfModule>

  Source

  設定過期頭資訊

  Expires headers tell the browser whether they should 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>

  關閉eTags標誌

  By removing the ETag header, you disable caches and browsers from being able to validate files, so they are forced to rely on your Cache-Control and Expires header. Source

<IfModule mod_headers.c>
    Header unset ETag
</IfModule>
FileETag None

 其它

  設定PHP變數

php_value <key> <val>

# For example:
php_value upload_max_filesize 50M
php_value max_execution_time 240

  Custom Error Pages

ErrorDocument 500 "Houston, we have a problem."
ErrorDocument 401 http://error.example.com/mordor.html
ErrorDocument 404 /errors/halflife3.html

  強制下載

  Sometimes you want to 強制 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:

  阻止下載

  Sometimes you want to 強制 the browser to display some content instead of downloading it.

<FilesMatch "\.(tex|log|aux)$">
    Header set Content-Type text/plain
</FilesMatch>

  執行跨域字型引用

  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 should always be UTF-8 encoded, no?

# Use UTF-8 encoding for anything served text/plain or text/html
AddDefaultCharset utf-8

# 強制 UTF-8 for a number of file formats
AddCharset utf-8 .atom .css .js .json .rss .vtt .xml

  Source

  切換PHP版本

  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 should switch the PHP version for you.

AddHandler application/x-httpd-php55 .php

# Alternatively, you can use AddType
AddType application/x-httpd-php55 .php

  禁止IE相容檢視

  Compatibility View in IE may affect how some websites are displayed. The following snippet should 強制 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>

  支援WebP圖片格式

  If WebP images are supported and an image with a .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 On
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{DOCUMENT_ROOT}/$1.webp -f
RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1]

  Source

相關文章