歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> 21個非常有用的.htaccess提示和技巧

21個非常有用的.htaccess提示和技巧

日期:2017/2/27 16:05:52   编辑:Linux教程
Apache Web 服務器可以通過 .htaccess 文件來操作各種信息,這是一個目錄級配置文件的默認名稱,允許去中央化的 Web 服務器配置管理。可用來重寫服務器的全局配置。該文件的目的就是為了允許單獨目錄的訪問控制配置,例如密碼和內容訪問。 下面是 21 個非常有用的 .htaccess 配置的提示和技巧:

1. 定制目錄的 Index 文件

DirectoryIndex index.html index.php index.htm
你可以使用上面的配置來更改目錄的默認頁面,例如你將這個腳本放在 foo 目錄,則用戶請求 /foo/ 時候就會訪問 /foo/index.html。

2. 自定義錯誤頁

ErrorDocument 404 errors/404.html
當用戶訪問頁面報錯時,例如頁面找不到你希望顯示自定義的錯誤頁面,你可以通過這種方法來實現。或者是動態的頁面:
ErrorDocument 404 /psych/cgi-bin/error/error?404

3. 控制訪問文件和目錄的級別

.htaccess 經常用來限制和拒絕訪問某個文件和目錄,例如我們有一個 includes 文件夾,這裡存放一些腳本,我們不希望用戶直接訪問這個文件夾,那麼通過下面的腳本可以實現:
# no one gets in here!
deny from all
上述腳本是拒絕所有的訪問,你也可以根據IP段來拒絕:
# no nasty crackers in here!
order deny,allow
deny from all
allow from 192.168.0.0/24
# this would do the same thing..
#allow from 192.168.0
一般這些方法是通過防火牆來處理,但在一個生產環境中的服務器來說,這樣的調整非常方便。 有時候你只是想禁止某個ip訪問:
# someone else giving the ruskies a bad name..
order allow,deny
deny from 83.222.23.219
allow from all

4. 修改環境變量

環境變量包含了服務器端 CGI 的一些擴展信息,可使用 SetEnv 和 UnSetEnv 進行設置以及取消設置.
SetEnv SITE_WEBMASTER "Jack Sprat"
SetEnv SITE_WEBMASTER_URI mailto:[email protected]

UnSetEnv REMOTE_ADDR

5. 301 重定向

如果你希望某個頁面跳轉到新的頁面:
Redirect 301 /old/file.html http://yourdomain.com/new/file.html
下面可以實現對整個路徑的重定向
RedirectMatch 301 /blog(.*) http://yourdomain.com/$1

6. 通過 .htaccess 實現緩存策略

通過設置在浏覽器上緩存靜態文件可以提升網站的性能:
# year
<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>
#2 hours
<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 對輸出進行壓縮

在 .htaccess 中添加下面的代碼可以將所有的 css、js 和 html 使用 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 模塊,你可以使用下面腳本來判斷 Web 服務器是否提供 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>
如果 Web 服務器不支持 mod_deflate ,那麼可使用下面方法:
<FilesMatch "\.(txt|html|htm|php)">
	php_value output_handler ob_gzhandler
</FilesMatch>
更多關於壓縮的內容請閱讀: Compressing PHP, CSS, JavaScript(JS).

8. 強制要求使用 HTTPS 訪問

通過以下腳本可以強制整個網站必須使用 https 方式訪問:
RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

9. URL 重寫

例如要將 product.php?id=12 重寫為 product-12.html
RewriteEngine on
RewriteRule ^product-([0-9]+)\.html$ product.php?id=$1
將 product.php?id=12 重寫為 product/ipod-nano/12.html
RewriteEngine on
RewriteRule ^product/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ product.php?id=$2
重定向沒有 www 到有 www 的 URL 地址:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^viralpatel\.net$
RewriteRule (.*) http://www.viralpatel.net/$1 [R=301,L]
重寫 yoursite.com/user.php?username=xyz 到 yoursite.com/xyz
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ user.php?username=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ user.php?username=$1
重定向某個域名到一個 public_html 裡新的子文件夾:
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 *
更多詳情 Denying/Allowing directory listing.

11. 添加新的 MIME-Types

MIME-types 依賴於文件的擴展名,未能被識別的文件擴展名會當成文本數據傳輸
AddType application/x-endnote-connection enz
AddType application/x-endnote-filter enf
AddType application/x-spss-savefile sav

12. 防盜鏈

你不希望別人網站引用你站內的圖片、css 等靜態文件,也就是傳說中的防盜鏈,可以使用如下腳本:
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{REQUEST_URI} !^/(wp-login.php|wp-admin/|wp-content/plugins/|wp-includes/).* [NC]
RewriteCond %{HTTP_REFERER} !^http://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. 設置服務器時區(GMT)

SetEnv TZ America/Indianapolis

17. 強制 “File Save As” 提示

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

18. 保護單個文件

正常情況下 .htaccess 可用於限制整個目錄的訪問,但也可以只限制某個文件:
<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

通過環境變量來設置 Cookie
Header set Set-Cookie "language=%{lang}e; path=/;" env=lang
基於請求設置 Cookie,該代碼發送 Set-Cookie 頭用於設置 Cookie 值為第二個括號裡的匹配項
RewriteEngine On
RewriteBase /
RewriteRule ^(.*)(de|es|fr|it|ja|ru|en)/$ - [co=lang:$2:.yourserver.com:7200:/]

20. 設置自定義的響應 Headers

Header set P3P "policyref=\"http://www.askapache.com/w3c/p3p.xml\""
Header set X-Pingback "http://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