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

18 個實用的 .htaccess 技巧,Apache 站長收藏必備

.htaccess 是 Apache 特有的目錄級設定檔,能操控伺服器上許多行為,例如存取控制、網址重導。以下整理 18 條常用寫法。

提醒:動手前務必先備份,這個檔案一旦寫錯,後果可能出乎意料。

網址正規化

1. 移除網址中的 www(相傳對 SEO 有利):

RewriteEngine On
RewriteCond %{HTTP_HOST} !^ijinfa.cn$ [NC]
RewriteRule ^(.*)$ https://ijinfa.cn/$1 [L,R=301]

2. 反過來強制使用 www:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^ijinfa.cn [NC]
RewriteRule ^(.*)$ https://www.ijinfa.cn/$1 [L,R=301]

12. 拿掉 WordPress 分類路徑中的 /category/:

RewriteRule ^category/(.+)$ https://www.yourblog.com/$1 [R=301,L]

14. 把含日期的舊式永久連結 301 導向 /%postname%/:

RedirectMatch 301 /([0-9]+)/([0-9]+)/([0-9]+)/(.*)$ https://www.domain.com/$4

防盜鏈與錯誤頁

3. 圖片防盜鏈:

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^https://(.+\.)?mysite\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*\.(jpe?g|gif|bmp|png)$ /images/nohotlink.jpg [L]

5. 自訂錯誤頁:

ErrorDocument 400 /errors/badrequest.html
ErrorDocument 401 /errors/authreqd.html
ErrorDocument 403 /errors/forbid.html
ErrorDocument 404 /errors/notfound.html
ErrorDocument 500 /errors/serverr.html

安全與存取控制

9. 禁止列出目錄內容:Options -Indexes

15. 攔掉機器人留言(阻絕大量垃圾評論):

RewriteEngine On
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REQUEST_URI} .wp-comments-post\.php*
RewriteCond %{HTTP_REFERER} !.*yourblog.com.* [OR]
RewriteCond %{HTTP_USER_AGENT} ^$
RewriteRule (.*) ^https://%{REMOTE_ADDR}/$ [R=301,L]

17. 只允許自己的 IP 進入 wp-admin:

AuthUserFile /dev/null
AuthGroupFile /dev/null
AuthName "Example Access Control"
AuthType Basic
<LIMIT GET>
order allow, deny
deny from all
allow from xx.xx.xx.xx
</LIMIT>

18. 把特定 IP 加黑:

<Limit GET POST>
order allow,deny
deny from 222.69.116.166
allow from all
</Limit>

效能優化

10. 壓縮靜態檔案:

AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml application/xhtml+xml text/javascript text/css application/x-javascript
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4.0[678] no-gzip
BrowserMatch bMSIE !no-gzip !gzip-only-text/html

13. 啟用瀏覽器快取:

FileETag MTime Size
<ifmodule mod_expires.c>
  <filesmatch "\.(jpg|gif|png|css|js)$">
    ExpiresActive on
    ExpiresDefault "access plus 1 year"
  </filesmatch>
</ifmodule>

其他實用小技巧

4. 把 WordPress 的 feed 導向 Feedburner;6. 強制下載 xls、eps 等檔案;7. 把 PHP 錯誤寫進 php_error.log 而不顯示給訪客;8. 隱藏網址中的副檔名;11. 為 html/css/js 自動補上 UTF-8 編碼;16. 用 302 把訪客導到 maintenance.html 維護頁(記得把自己的 IP 排除在外)。

18 條寫法裡,第 16 條的維護頁與第 13 條的快取設定,是實際維運時最常回頭翻閱的兩條。

Copyright © Linux教程網 All Rights Reserved