Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux教程

21 個實用的 .htaccess 技巧

Apache 的 .htaccess 是目錄層級的設定檔,讓管理員不必動到全域設定就能做去中心化的調整,最常用於目錄級的存取控制(例如密碼保護)。以下 21 條是實務上最常翻回來查的寫法。

1. 自訂目錄預設首頁

DirectoryIndex index.html index.php index.htm

請求 /foo/ 時即會去找 /foo/index.html。

2. 自訂錯誤頁

ErrorDocument 404 errors/404.html
ErrorDocument 404 /psych/cgi-bin/error/error?404

靜態頁面或動態程式都可以。

3. 控制檔案與目錄的存取

# 全部拒絕
deny from all
# 只允許特定網段
order deny,allow
deny from all
allow from 192.168.0.0/24
# 只封鎖單一 IP
order allow,deny
deny from 83.222.23.219
allow from all

這類需求通常由防火牆處理,但在生產環境上用 .htaccess 調整確實方便。

4. 設定環境變數

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

5. 301 重定向

Redirect 301 /old/file.html https://yourdomain.com/new/file.html
RedirectMatch 301 /blog(.*) https://yourdomain.com/$1

6. 用 .htaccess 設定快取

# 快取一年
<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>
# 快取兩小時
<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. 用 GZIP 壓縮輸出

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

前提是啟用 mod_gzip。若要用 mod_deflate:

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

伺服器兩者都不支援時,可退回 PHP 層:

<FilesMatch "\.(txt|html|htm|php)">
php_value output_handler ob_gzhandler
</FilesMatch>

8. 強制使用 HTTPS

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

9. URL 重寫

RewriteEngine on
RewriteRule ^product-([0-9]+)\.html$ product.php?id=$1
RewriteEngine on
RewriteRule ^product/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ product.php?id=$2
# 無 www 導向有 www
RewriteEngine On
RewriteCond %{HTTP_HOST} ^viralpatel\.net$
RewriteRule (.*) https://www.viralpatel.net/$1 [R=301,L]
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ user.php?username=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ user.php?username=$1
# 整個網域導向 new 子目錄
RewriteEngine On
RewriteCond %{HTTP_HOST} ^test\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.test\.com$
RewriteCond %{REQUEST_URI} !^/new/
RewriteRule (.*) /new/$1

10. 禁止列出目錄內容

Options -Indexes
# 或
IndexIgnore *

11. 新增 MIME 類型

AddType application/x-endnote-connection enz
AddType application/x-endnote-filter enf
AddType application/x-spss-savefile sav

未被辨識的副檔名會被當成純文字傳輸。

12. 防盜鏈

RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{REQUEST_URI} !^/(wp-login.php|wp-admin/|wp-content/plugins/|wp-includes/).* [NC]
RewriteCond %{HTTP_REFERER} !^https://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. 限制上傳大小(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

四個參數分別是檔案大小、POST 資料大小、傳輸時間(秒)與解析上傳資料的最長時間(秒)。

14. 禁止執行腳本

Options -ExecCGI
AddHandler cgi-script .php .pl .py .jsp .asp .htm .shtml .sh .cgi

15. 指定字元集與語言

AddDefaultCharset UTF-8
DefaultLanguage en-US

16. 設定伺服器時區

SetEnv TZ America/Indianapolis

17. 強制跳出「另存新檔」

AddType application/octet-stream .avi .mpg .mov .pdf .xls .mp4

18. 只保護單一檔案

<Files quiz.html>
order deny,allow
deny from all
AuthType Basic
AuthName "Characterology Student Authcate"
AuthLDAP on
AuthLDAPServer ldap://directory.characterology.com/
AuthLDAPBase "ou=Student, o=Characterology University, c=au"
require valid-user
satisfy any
</Files>

19. 設定 Cookie

Header set Set-Cookie "language=%{lang}e; path=/;" env=lang
RewriteEngine On
RewriteBase /
RewriteRule ^(.*)(de|es|fr|it|ja|ru|en)/$ - [co=lang:$2:.yourserver.com:7200:/]

20. 自訂回應標頭

Header set P3P "policyref=\"https://www.askapache.com/w3c/p3p.xml\""
Header set X-Pingback "https://www.askapache.com/xmlrpc.php"
Header set Content-Language "en-US"
Header set Vary "Accept-Encoding"

21. 依 User-Agent 封鎖請求

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
Copyright © Linux教程網 All Rights Reserved