HOME | 其他語言 | htaccess 常用命令

htaccess 常用命令

2016/07/15/17:00 , Post in 其他語言 , 評論(0) , 引用(0) , 閱讀(1280) , Via 本站原創
本文翻譯自 : https://github.com/phanan/htaccess

原始翻譯 : http://nitroxenon.com/htaccess-compilation

請確認你的 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]


強制不使用 WWW

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

強制 HTTPS

如果你的伺服器經過 TLS Proxy ,這個將會很實用

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


強制 “/" 結尾

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


單頁重新導向

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


單一目錄別名 (Alias)

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


檔案別名 (Alias) (重新導向)

RewriteEngine On
RewriteRule ^$ index.fcgi/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L]


這個例子在幾個目錄裏面有一個 index.fcgi 檔案,如果改目錄有任何請求錯誤,將會重新導向到 index.fcgi 檔案。

重新導向整個網站

Redirect 301 / http://newsite.com/

使用效果 :

www.oldsite.com/some/path/page.html

會變成

www.newsite.com/some/path/page.html

如果你要網站搬家,這個功能十分實用

移除副檔名

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


使用效果 :

example.com/users.php

會變成

example.com/user

安全性

禁止訪問

Apache 2.2
Deny from all

Apache 2.4
Require all denied


請注意,使用後你將無法存取網站

禁止訪問 (除了你)

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 是你的 IP,能使用 IP 範圍


禁止垃圾留言者訪問

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


禁止訪問隱藏目錄和檔案

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


禁止訪問備份和原始碼目錄

<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>


禁止目錄瀏覽 (Index)

Options All -Indexes
Options All -Indexes


禁止圖片熱鏈

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]


密碼保護目錄

首先,你需要新增一個 .htpasswd 檔案

htpasswd -c /home/fellowship/.htpasswd boromir

然後修改 .htaccess 檔案

AuthType Basic
AuthName "One does not simply"
AuthUserFile /home/fellowship/.htpasswd
Require valid-user
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>


效能

壓縮文字檔案

<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~-]{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>


設置頁面到期標頭

<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-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 (禁止認證緩存)

<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


自定義錯誤頁面

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


強制下載指定類型檔案

//強制下載 MARKDOWN 檔案
<Files *.md>
    ForceType application/octet-stream
    Header set Content-Disposition attachment
</Files>


防止指定類型檔案下載

有時候你想在瀏覽器觀看檔案內容,但是瀏覽器強制下載,使用此方法可避免此問題。
<FilesMatch "\.(tex|log|aux)$">
    Header set Content-Type text/plain
</FilesMatch>


允許跨站字形檔案

<IfModule mod_headers.c>
    <FilesMatch "\.(eot|otf|ttc|ttf|woff)$">
        Header set Access-Control-Allow-Origin "*"
    </FilesMatch>
</IfModule>

切換 PHP 版本

# Alternatively, you can use AddType

# Alternatively, you can use AddType



發表評論

暱稱

網址

電郵

開啟HTML 開啟UBB 開啟表情 隱藏 記住我 [登入] [註冊]