Một số cấu hình file .htaccess
1. .htaccess là gì?
1.1. .htaccess là gì
.htaccess là một file cấu hình sử dụng cho các web server chạy Apache. .htaccess dùng để thiết lập các tùy chọn: thực thi hay loại bỏ các chức năng, tính năng của Apache
1.2. Ý nghĩa ký hiệu định nghĩa trong .htaccess
# : cho phép server bỏ qua dòng này
[F] : Forbidden, hướng dẫn server trả về lỗi 403 cho client
[L] : Last rule, hướng dẫn server ngừng ghi lại sau khi một chỉ thị đã được xử lý
[N] : Next, chỉ dẫn cho Apache trả về luật rewrite cho tới khi tất cả các chỉ thị rewrite được hoàn tất.
[G]: Gone, chỉ dẫn server chuyển thông điệp Gone
[P]: Proxy, chỉ dẫn server sử dụng các request cung cấp bởi mod_proxy
[C]: Chain, chỉ dẫn server gắn luật trước với luật sau nó
[R]: Redirect, hướng dẫn Apache đưa ra một chuyển hướng
[NC]: No case, xác định bất cứ trường hợp nào liên quan tới nó là vô lý (Không thể xảy ra)
[PT]: Pas Through: chỉ dẫn mod_rewrite để vượt qua cơ chế ghi lại URL cho các xử lý xa hơn
[OR]: Or, là cú pháp logic bình thường (biểu thức kết hợp đúng khi một trong hai biểu thức con của nó đúng)
[NE]: No Escape: hướng dẫn server lọc đầu ra
[NS]: No Subresquest: hướng dẫn server giữ chỉ thị nếu là một request con từ bên trong
[QSA]: gắn thêm chuỗi truy vấn vào cuối URL
[S=x]: Skip: chỉ dẫn server dừng lại x luật
[E=variable:value]: Environment Variale: chỉ dẫn server thiết lập giá trị tài nguyên
[T=MIME-type]: Mime Type: mô tả loại mime của tài nguyên đích
[]: xác định một tập các ký tự trong đó bất cứ ký tự nào có trong ngoặc xuất hiện sẽ được match
[]+: tập các ký tự trong đó bất cứ kết hợp nào với nó cũng được match
[a-z] : match với tất cả các ký tự từ a-z, theo bảng chữ cái. Có thể có thêm: [a-zA-Z]
a{n}: xác định số ký tự sẽ mở rộng cùng với ký tự đầu, tức là khi match được ký tự đầu sẽ lấy thêm bao nhiêu ký tự tiếp theo. Ví dụ: x{3} sẽ lấy: x’s, xad, …
a{n,} : như a{n} nhưng có thể lấy 3 hoặc nhiều hơn
a{n,m}: như a{n} nhưng sẽ lấy trong khoảng từ n tới m
(): nhóm các ký tự lại với nhau, xem chúng như 1 đơn vị đơn lẻ
^: ghi chú bắt đầu chuỗi regex
$: ghi chú kết thúc chuỗi regex
? : cho phép chọn lựa ký tự.Ví dụ: monzas? sẽ match với monza hoặcmonzas
! : mô tả một phủ định, sẽ match với tất cả thứ gì khác với các ký tự sau !
. : thể hiện cho bất cứ ký tự đơn nào
+: match với một hoặc nhiều ký tự
*: match với 0 hoặc nhiều ký tự
|: phép hoặc logic
: thêm vào trước các ký tự đặc biệt để có thể sử dụng chúng như các ký tự bình thường
.* : không có ký tự nào hoặc nhiều ký tự bất kỳ
^$: định nghĩa một chuỗi rỗng
^.*$: sử dụng để match mọi thứ
[^/.]: định nghĩa 1 ký tự là “/” hoặc “.”
[^/.]+: định nghĩa bất cứ số lượng ký tự nào chứa “/” hoặc “.”
http://: là một chuỗi bình thường
^domain.*: định nghĩa một chuỗi bắt đầu với “domain”
^domain.com$: xác định sự mở rộng của chuỗi “domain.com”
-d: kiểm tra nếu chuỗi là một directory
-f: kiểm tra nếu một chuỗi là một file
-s: kiểm tra nếu file trong chuỗi kiểm tra có 1 giá trị khác 0
1.3. Mã redirect
301 – Move permanently
302 – Move temporarily
403 – Forbidden
404 – Not found
410 – Gone
1.4. Cách sử dụng .htaccess
Tạo file .htaccess (chú ý đây là tên đầy đủ, không phải là phần mở rộng), tiến hành các thiết lập cấu hình trong file và đặt ở trong thư mục mong muốn thực hiện các cấu hình đó.
Ví dụ:
AuthName "Member's Area Name"AuthUserFile /path/to/password/file/.htpasswdAuthType Basicrequire valid-userErrorDocument 401 /error_pages/401.htmlAddHandler server-parsed .htmlVí dụ trên cấu hình sử dụng password bảo vệ thư mục và chuyển hướng tới trang 401.html khi gặp lỗi 401.
Chú ý:
- Upload file .htaccess ở chế độ ASCII thay vì chế độ BINARY hay các chế độ khác do cơ chế chuyển dữ liệu ở các chế độ là khác nhau.
- Việc cấp quyền truy cập, sử dụng và thực thi file .htaccess có thể gây ra lỗi, cài đặt quyền 755 hoặc quyền thực thi với file
- Comment lại các thông tin cấu hình quan trọng để dễ dàng cho người tiếp quản sau này hoặc cho chính bản than khi phải cấu hình lại hoặc khắc phục sự cố nào đó
2. Những cấu hình cần thiết
2.1. Enable basic rewriting
Server có thể không bật chế độ “mod_rewite” mặc định, để đảm bảo chế độ này được bật, thêm vào file .htaccess tại thư mục root:
# enable basic rewriting2.2. Enable Symbolic links
RewriteEngine on
Xem về Symbolic links tại: http://en.wikipedia.org/wiki/Symbolic_link. Để chế độ này hoặc động, tính năng: AllowOverride Options cần được enable.
# enable symbolic links2.3. Enable AllowOverride
Options +FollowSymLinks
Đối với các chỉ thị cần tính năng AllowOverride để thực thi như: FollowSymlinks, … Khi cần enable tính năng này tại một thư mục nào đó, ta thêm vào .htaccess (Có thể cấu hình tại file server để áp dụng toàn bộ):
# enable allowoverride privileges2.4. Đặt tên lại file .htaccess
<Directory /www/replace/this/with/actual/directory>
AllowOverride Options
</Directory>
Không phải mọi hệ thống đều thích định dạng .htaccess, có thể thay đổi tên này (thực hiện trên file cấu hình của server):
# rename htaccess filesKhi thay đổi tên file .htaccess, cần cập nhật tất cả các cấu hình liên quan. Ví dụ: nếu bạn bảo vệ .htaccess với FilesMatch, định dạng lại file này (với .htaccess đã đổi thành: ht.access):
AccessFileName ht.access
# protect renamed htaccess files2.5. Giữ lại các luật đã được định nghĩa trong httpd.conf
<FilesMatch "^ht.">
Order deny,allow
Deny from all
</FilesMatch>
Tiết kiệm thời gian và nỗ lực định nghĩa lại các luật lặp lại cho nhiều host ảo với chỉ 1 file httpd.conf, để đơn giản hơn ta cấu hình .htaccess kế thừa tập luật từ httpd.conf
RewriteOptions Inherit3. Hiệu năng
3.1. Tăng hiệu năng thông qua AllowOverride
Việc cấu hình AllowOverride ở thư mục gốc, server sẽ phải tìm kiếm ở tất cả các thư mục để xem nơi nào .htaccess tồn tại, điều này làm chậm tốc độ xử lý. Để hạn chế điều này, disable chế độ AllowOverride tại thư mục gốc và bật lên ở những nơi cần dùng, để disable:
# increase performance by disabling allowoverride3.2. Tăng hiệu năng bằng cách truyền tập các ký tự
AllowOverride None
# pass the default character set3.3. Tăng hiệu năng bởi việc bảo vệ bandwidth
AddDefaultCharset utf-8
# preserve bandwidth for PHP enabled servers3.4. Disable chữ ký server
<ifmodule mod_php4.c>
php_value zlib.output_compression 16386
</ifmodule>
# disable the server signature3.5. Cài đặt server timezone
ServerSignature Off
# set the server timezone3.6. Đặt địa chỉ email cho quản trị server
SetEnv TZ America/Washington
# set the server administrator emailSetEnv SERVER_ADMIN default@domain.com3.7. Tăng tốc độ duyệt site bằng việc enable file caching
# cache images and flash content for one month
<FilesMatch ".(flv|gif|jpg|jpeg|png|ico|swf)$">
Header set Cache-Control "max-age=2592000"
</FilesMatch>
# cache text, css, and javascript files for one week
<FilesMatch ".(js|css|pdf|txt)$">
Header set Cache-Control "max-age=604800"
</FilesMatch>
# cache html and htm files for one day
<FilesMatch ".(html|htm)$">
Header set Cache-Control "max-age=43200"
</FilesMatch>
# implement minimal caching during site development
<FilesMatch ".(flv|gif|jpg|jpeg|png|ico|js|css|pdf|swf|html|h tm|txt)$">
Header set Cache-Control "max-age=5"
</FilesMatch>
# explicitly disable caching for scripts and other dynamic files
<FilesMatch ".(pl|php|cgi|spl|scgi|fcgi)$">
Header unset Cache-Control
</FilesMatch>
# alternate method for file caching
ExpiresActive On
ExpiresDefault A604800 # 1 week
ExpiresByType image/x-icon A2419200 # 1 month
ExpiresByType application/x-javascript A2419200 # 1 month
ExpiresByType text/css A2419200 # 1 month
ExpiresByType text/html A300 # 5 minutes
# disable caching for scripts and other dynamic filesConvert common time intervals into seconds:
<FilesMatch ".(pl|php|cgi|spl|scgi|fcgi)$">
ExpiresActive Off
</FilesMatch>
- 300 = 5 minutes
- 2700 = 45 minutes
- 3600 = 1 hour
- 54000 = 15 hours
- 86400 = 1 day
- 518400 = 6 days
- 604800 = 1 week
- 1814400 = 3 weeks
- 2419200 = 1 month
- 26611200 = 11 months
- 29030400 = 1 year = never expires
# set the default language
DefaultLanguage en-US
# set the default character set3.9. Mô tả MIME
AddDefaultCharset UTF-8
MIME types là tập các phần mở rộng của file, server cần biết tham số này để biết nó đang thao tác với loại file nào. Sử dụng “AddType” để thêm một MIME, tham số tiếp theo là loại MIME và cuối cùng là phần mở rộng của file. Ví dụ với file MP3 hoặc SWF:
AddType application/x-shockwave-flash swfAddType application/x-shockwave-flash .swfMột số loại file không cho chạy trực tiếp trên trình duyệt mà yêu cầu download về máy, loại MIME cần thiết lập là: application/octec-stream
AddType video/x-flv .flv
AddType image/x-icon .ico
Danh sách các MIME và loại file tương ứng:
AddType text/html .html .htm3.10. Gửi kiểu mã hóa và header không cần thẻ meta
AddType text/plain .txt
AddType text/richtext .rtx
AddType text/tab-separated-values .tsv
AddType text/x-setext .etx
AddType text/x-server-parsed-html .shtml .sht
AddType application/macbinhex-40 .hqx
AddType application/netalivelink .nel
AddType application/netalive .net
AddType application/news-message-id
AddType application/news-transmission
AddType application/octet-stream .bin .exe
AddType application/oda .oda
AddType application/pdf .pdf
AddType application/postscript .ai .eps .ps
AddType application/remote-printing
AddType application/rtf .rtf
AddType application/slate
AddType application/zip .zip
AddType application/x-mif .mif
AddType application/wita
AddType application/wordperfect5.1
AddType application/x-csh .csh
AddType application/x-dvi .dvi
AddType application/x-hdf .hdf
AddType application/x-latex .latex
AddType application/x-netcdf .nc .cdf
AddType application/x-sh .sh
AddType application/x-tcl .tcl
AddType application/x-tex .tex
AddType application/x-texinfo .texinfo .texi
AddType application/x-troff .t .tr .roff
AddType application/x-troff-man .man
AddType application/x-troff-me .me
AddType application/x-troff-ms .ms
AddType application/x-wais-source .src
AddType application/x-bcpio .bcpio
AddType application/x-cpio .cpio
AddType application/x-gtar .gtar
AddType application/x-shar .shar
AddType application/x-sv4cpio .sv4cpio
AddType application/x-sv4crc .sv4crc
AddType application/x-tar .tar
AddType application/x-ustar .ustar
AddType application/x-director .dcr
AddType application/x-director .dir
AddType application/x-director .dxr
AddType application/x-onlive .sds
AddType application/x-httpd-cgi .cgi
AddType image/gif .gif .GIF
AddType image/ief .ief
AddType image/jpeg .jpeg .jpg .jpe .JPG
AddType image/tiff .tiff .tif
AddType image/x-cmu-raster .ras
AddType image/x-portable-anymap .pnm
AddType image/x-portable-bitmap .pbm
AddType image/x-portable-graymap .pgm
AddType image/x-portable-pixmap .ppm
AddType image/x-rgb .rgb
AddType image/x-xbitmap .xbm
AddType image/x-xpixmap .xpm
AddType image/x-xwindowdump .xwd
AddType audio/basic .au .snd
AddType audio/x-aiff .aif .aiff .aifc
AddType audio/x-wav .wav
AddType audio/x-pn-realaudio .ram
AddType audio/x-midi .mid
AddType video/mpeg .mpeg .mpg .mpe
AddType video/quicktime .qt .mov
AddType video/x-msvideo .avi
AddType video/x-sgi-movie .movie
AddType message/external-body
AddType message/news
AddType message/partial
AddType message/rfc822
AddType multipart/alternative
AddType multipart/appledouble
AddType multipart/digest
AddType multipart/mixed
AddType multipart/parallel
AddType x-world/x-vrml .wrl
# send the language tag and default character set3.11. Giới hạn các request GET và PUT
# AddType 'text/html; charset=UTF-8' html
AddDefaultCharset UTF-8
DefaultLanguage en-US
# limit server request methods to GET and PUT3.12. Lựa chọn file xử lý theo phương thức request tới server
Options -ExecCGI -Indexes -All
RewriteEngine on
RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK|OPTIONS|HEAD) RewriteRule .* - [F]
# process files according to server request method3.13. Thực thi một định dạng file bằng 1 cgi script
Script PUT /cgi-bin/upload.cgi
Script GET /cgi-bin/download.cgi
# execute all png files via png-script.cgi4. Các cấu hình bảo mật
Action image/png /cgi-bin/png-script.cgi
4.1. Ngăn cản truy cập file .htaccess
Khi người dùng cố tình truy nhập file .htaccess sẽ trả về lỗi 403, có nhiều cách để cấu hình, có thể cấu hình file với CHMOD là 644 hoặc thêm đoạn mã sau:
# secure htaccess file4.2. Ngăn cản truy cập tới một file đặc biệt
<Files .htaccess>
order allow,deny
deny from all
</Files>
Để chặn truy nhập vào một file đặc biệt nào đó, thêm đoạn mã sau vào file .htaccess, giả sử là file secretfile.jpg
# prevent viewing of a specific file4.3. Chặn truy cập tới nhiều file
<files secretfile.jpg>
order allow,deny
deny from all
</files>
<FilesMatch ".(htaccess|htpasswd|ini|phps|fla|psd|log|sh) $">4.4. Chống browse thư mục trái phép
Order Allow,Deny
Deny from all
</FilesMatch>
Đảm bảo người dùng không có đủ quyền không thể xem toàn bộ trang web dưới dạng Directory listing.
# disable directory browsingNgược lại để cho phép người dùng có thể xem dưới dạng này, sử dụng:
Options All –Indexes
# enable directory browsingNgăn cản server listing directory:
Options All +Indexes
# prevent folder listingNgăn cản truy nhập vào các file có định dạng nào đó, sử dụng IndexIgnore
IndexIgnore *
# prevent display of select file types4.5. Thay đổi trang index mặc định
IndexIgnore *.wmv *.mp4 *.avi *.etc
Có thể thay vì sử dụng trang index một cách mặc định, ta cấu hình cho server nhận một file khác có chức năng tương tự như file index (ở đâylà business.html)
# serve alternate default index pageHoặc cho một loạt file đều có thể là file index, server sẽ tìm kiếm và đưa ra file đầu tiên tìm được là file index
DirectoryIndex business.html
# serve first available alternate default index page from series4.6. Ngụy trang cho định dạng script
DirectoryIndex filename.html index.cgi index.pl default.htm
Để tăng cường tính bảo mật, việc ngụy trang cho ngôn ngữ kịch bản bằng việc thay đổi phần mở rộng cũng là một yếu tố cần xét đến:
# serve foo files as php files4.7. Giới hạn truy cập tới mạng LAN
AddType application/x-httpd-php .foo
# serve foo files as cgi files
AddType application/x-httpd-cgi .foo
# limit access to local area network4.8. Bảo vệ thư mục bằng địa chỉ IP và/hoặc domain
<Limit GET POST PUT>
order deny,allow
deny from all
allow from 192.168.0.0/33
</Limit>
Cấu hình cho phép các truy cập ngoại trừ truy cập từ địa chỉ: x.y.z.v và từ domain.com
# allow all except those indicated hereNgược lại với cấu hình bên trên, từ chối tất cả IP truy cập ngoại trừ x.y.z.v và domain.com
<Limit GET POST PUT>
order allow,deny
allow from all
deny from x.y.z.v
deny from .*domain.com.*
</Limit>
# deny all except those indicated hereNgoài ra, cũng có thể tiết kiệm băng thông bằng cách block một số định dạng file đặc biệt như: .jpg, .zip, ,mp3, … từ các server ngoài (ở đây là abc và xyz)
<Limit GET POST PUT>
order deny,allow
deny from all
allow from x.y.z.v
allow from .*domain.com.*
</Limit>
# block visitors referred from indicated domains4.9. Ngăn cản hoặc cho phép truy cập domain theo dải địa chỉ IP
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_REFERER} abc.com [NC,OR]
RewriteCond %{HTTP_REFERER} xyz.com [NC,OR]
RewriteRule .* - [F]
</ifModule>
Có nhiều phương pháp để block một dải địa chỉ IP bằng cách cấu hình .htaccess. Cách thức đầu tiên có thể sử dụng sô CIDR (Classess Inter-Domain Routing) của dải IP, cách này hiệu quả để block các mega-spammer như RIPE, Optinet, …
# block IP range by CIDR numberĐể cho phép bởi CIDR:
<Limit GET POST PUT>
order allow,deny
allow from all
deny from 10.1.0.0/16
deny from 80.0.0/8
</Limit>
# allow IP range by CIDR numberMột biện pháp khác chúng ta có thể block dải IP đầu vào liên quan tới số truncating cho tới khi dải mong muốn xuất hiện
<Limit GET POST PUT>
order deny,allow
deny from all
allow from 10.1.0.0/16
allow from 80.0.0/8
</Limit>
# block IP range by address truncationCho phép địa chỉ IP theo cách này:
<Limit GET POST PUT>
order allow,deny
allow from all
deny from 99.88.77.66
deny from 99.88.77.*
deny from 99.88.*.*
deny from 99.*.*.*
</Limit>
# allow IP range by address truncation4.10. Chặn hoặc cho phép nhiều địa chỉ trong cùng 1 dòng
<Limit GET POST PUT>
order deny,allow
deny from all
allow from 99.88.77.66
allow from 99.88.77.*
allow from 99.88.*.*
allow from 99.*.*.*
</Limit>
Block:
# block two unique IP addresses
deny from 99.88.77.66 11.22.33.44
# block three ranges of IP addressesAllow:
deny from 99.88 99.88.77 11.22.33
# allow two unique IP addresses
allow from 99.88.77.66 11.22.33.44
# allow three ranges of IP addresses4.11. Các luật khác sử dụng để block hay allow địa chỉ IP
allow from 99.88 99.88.77 11.22.33
Có một số luật khác có thể sử dụng:
# block a partial domain via network/netmask values
deny from 99.1.0.0/255.255.0.0
# block a single domain
deny from 99.88.77.66
# block domain.com but allow sub.domain.com4.12. Ngừng các hotlinking, luân chuyển nội dung server
order deny,allow
deny from domain.com
allow from sub.domain.com
Mục tiêu nhằm giúp các quản trị viên ngăn cản các website bên ngoài sử dụng trực tiếp các hình ảnh, nội dung, link, … từ website của mình. Vì dạng này làm tốn băng thông.
Sử dụng chế độ này khi đã kích hoạt mod_rewrite.
# stop hotlinking and serve alternate contentĐể chuyển giao một page lỗi thay vì một số hình ảnh như eatme.jpg như bên trên, thay dòng RewriteRule bằng dòng:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?domain\.com/.*$ [NC]
RewriteRule .*\.(gif|jpg)$ http://www.domain.com/eatme.jpg [R,NC,L]
</ifModule>
# serve a standard 403 forbidden error pageĐể cho phép một domain ngoài có thể sử dụng hotlinking (goodsite chẳng hạn), thêm dòng cấu hình:
RewriteRule .*.(gif|jpg)$ - [F,L]
# allow linking from the following site4.13. Chặn Evil Robots, Site Rippers, và Offline Browsers
RewriteCond %{HTTP_REFERER} !^http://(www.)?goodsite.com/.*$ [NC]
RewriteEngine OnThay vì gửi một thông báo thân thiện, có thể gửi lại mộ website:
RewriteCond %{HTTP_USER_AGENT} ^BlackWidow [OR]
RewriteCond %{HTTP_USER_AGENT} ^Bot\ mailto:craftbot@yahoo.com [OR]
RewriteCond %{HTTP_USER_AGENT} ^ChinaClaw [OR]
RewriteCond %{HTTP_USER_AGENT} ^Custo [OR]
RewriteCond %{HTTP_USER_AGENT} ^DISCo [OR]
RewriteCond %{HTTP_USER_AGENT} ^Download\ Demon [OR]
RewriteCond %{HTTP_USER_AGENT} ^eCatch [OR]
RewriteCond %{HTTP_USER_AGENT} ^EirGrabber [OR]
RewriteCond %{HTTP_USER_AGENT} ^EmailSiphon [OR]
RewriteCond %{HTTP_USER_AGENT} ^EmailWolf [OR]
RewriteCond %{HTTP_USER_AGENT} ^Express\ WebPictures [OR]
RewriteCond %{HTTP_USER_AGENT} ^ExtractorPro [OR]
RewriteCond %{HTTP_USER_AGENT} ^EyeNetIE [OR]
RewriteCond %{HTTP_USER_AGENT} ^FlashGet [OR]
RewriteCond %{HTTP_USER_AGENT} ^GetRight [OR]
RewriteCond %{HTTP_USER_AGENT} ^GetWeb! [OR]
RewriteCond %{HTTP_USER_AGENT} ^Go!Zilla [OR]
RewriteCond %{HTTP_USER_AGENT} ^Go-Ahead-Got-It [OR]
RewriteCond %{HTTP_USER_AGENT} ^GrabNet [OR]
RewriteCond %{HTTP_USER_AGENT} ^Grafula [OR]
RewriteCond %{HTTP_USER_AGENT} ^HMView [OR]
RewriteCond %{HTTP_USER_AGENT} HTTrack [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Image\ Stripper [OR]
RewriteCond %{HTTP_USER_AGENT} ^Image\ Sucker [OR]
RewriteCond %{HTTP_USER_AGENT} Indy\ Library [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^InterGET [OR]
RewriteCond %{HTTP_USER_AGENT} ^Internet\ Ninja [OR]
RewriteCond %{HTTP_USER_AGENT} ^JetCar [OR]
RewriteCond %{HTTP_USER_AGENT} ^JOC\ Web\ Spider [OR]
RewriteCond %{HTTP_USER_AGENT} ^larbin [OR]
RewriteCond %{HTTP_USER_AGENT} ^LeechFTP [OR]
RewriteCond %{HTTP_USER_AGENT} ^Mass\ Downloader [OR]
RewriteCond %{HTTP_USER_AGENT} ^MIDown\ tool [OR]
RewriteCond %{HTTP_USER_AGENT} ^Mister\ PiX [OR]
RewriteCond %{HTTP_USER_AGENT} ^Navroad [OR]
RewriteCond %{HTTP_USER_AGENT} ^NearSite [OR]
RewriteCond %{HTTP_USER_AGENT} ^NetAnts [OR]
RewriteCond %{HTTP_USER_AGENT} ^NetSpider [OR]
RewriteCond %{HTTP_USER_AGENT} ^Net\ Vampire [OR]
RewriteCond %{HTTP_USER_AGENT} ^NetZIP [OR]
RewriteCond %{HTTP_USER_AGENT} ^Octopus [OR]
RewriteCond %{HTTP_USER_AGENT} ^Offline\ Explorer [OR]
RewriteCond %{HTTP_USER_AGENT} ^Offline\ Navigator [OR]
RewriteCond %{HTTP_USER_AGENT} ^PageGrabber [OR]
RewriteCond %{HTTP_USER_AGENT} ^Papa\ Foto [OR]
RewriteCond %{HTTP_USER_AGENT} ^pavuk [OR]
RewriteCond %{HTTP_USER_AGENT} ^pcBrowser [OR]
RewriteCond %{HTTP_USER_AGENT} ^RealDownload [OR]
RewriteCond %{HTTP_USER_AGENT} ^ReGet [OR]
RewriteCond %{HTTP_USER_AGENT} ^SiteSnagger [OR]
RewriteCond %{HTTP_USER_AGENT} ^SmartDownload [OR]
RewriteCond %{HTTP_USER_AGENT} ^SuperBot [OR]
RewriteCond %{HTTP_USER_AGENT} ^SuperHTTP [OR]
RewriteCond %{HTTP_USER_AGENT} ^Surfbot [OR]
RewriteCond %{HTTP_USER_AGENT} ^tAkeOut [OR]
RewriteCond %{HTTP_USER_AGENT} ^Teleport\ Pro [OR]
RewriteCond %{HTTP_USER_AGENT} ^VoidEYE [OR]
RewriteCond %{HTTP_USER_AGENT} ^Web\ Image\ Collector [OR]
RewriteCond %{HTTP_USER_AGENT} ^Web\ Sucker [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebAuto [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebCopier [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebFetch [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebGo\ IS [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebLeacher [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebReaper [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebSauger [OR]
RewriteCond %{HTTP_USER_AGENT} ^Website\ eXtractor [OR]
RewriteCond %{HTTP_USER_AGENT} ^Website\ Quester [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebStripper [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebWhacker [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebZIP [OR]
RewriteCond %{HTTP_USER_AGENT} ^Wget [OR]
RewriteCond %{HTTP_USER_AGENT} ^Widow [OR]
RewriteCond %{HTTP_USER_AGENT} ^WWWOFFLE [OR]
RewriteCond %{HTTP_USER_AGENT} ^Xaldon\ WebSpider [OR]
RewriteCond %{HTTP_USER_AGENT} ^Zeus
RewriteRule ^.* - [F,L]
# send em to a hellish website of your choiceHoặc gửi một blackhold fake email:
RewriteRule ^.*$ http://www.hellish-website.com [R,L]
# send em to a virtual blackhole of fake email addressesCó thể chặn theo referrer, ở đây ta chặn iaea.org:
RewriteRule ^.*$ http://english-61925045732.spampoison.com [R,L]
RewriteCond %{HTTP_REFERER} ^http://www.iaea.org$Một số cách chặn khác:
RewriteRule !^http://[^/.]\.yourdomain\.com.* - [F,L]
# redirect any request for anything from spamsite to differentspamsite
RewriteCond %{HTTP_REFERER} ^http://.*spamsite.*$ [NC]
RewriteRule .* http://www.differentspamsite.com [R]
# redirect all requests from spamsite to an image of something at differentspamsite
RewriteCond %{HTTP_REFERER} ^http://.*spamsite.*$ [NC]
RewriteRule .* http://www.differentspamsite/something.jpg [R]
# redirect traffic from a certain address or range of addresses to another site4.14. Pass bảo vệ
RewriteCond %{REMOTE_ADDR} 192.168.10.*
RewriteRule .* http://www.differentspamsite.com/index.html [R]
Đặt password bảo vệ là một biện pháp bảo vệ nội dung website và chỉ cho phép người dùng nội bộ có thể truy nhập nội dung.
Được hỗ trợ bởi Apache. Giúp giới hạn người dùng trong những khu vực khác nhau của một website.
Khi một thư mục được đặt password thì toàn bộ thư mục con và file trong thư mục sẽ được đặt password như vậy.
Nội dung file .htaccess để thư mục chứa nó được bảo vệ bởi mật khẩu:
username:encryptedpassword
fred_smithredfaceCF9Pam/MXJg2
Tham khảo trang sau (tạo password bảo vệ thư mục):
http://www.thejackol.com/scripts/htpasswdgen.php
# password-protect single file
<Files secure.php>
AuthType Basic
AuthName "Prompt"
AuthUserFile /home/path/.htpasswd
Require valid-user
</Files>
# password-protect multiple files
<FilesMatch "^(execute|index|secure|insanity|biscuit)*$">
AuthType basic
AuthName "Development"
AuthUserFile /home/path/.htpasswd
Require valid-user
</FilesMatch>
# password-protect the directory in which this htaccess rule resides
AuthType basic
AuthName "This directory is protected"
AuthUserFile /home/path/.htpasswd
AuthGroupFile /dev/null
Require valid-user
# password-protect directory for every IP except the one specified4.15. Tự động đặt CHMOD cho các loại file
# place in htaccess file of a directory to protect that entire directory
AuthType Basic
AuthName "Personal"
AuthUserFile /home/path/.htpasswd
Require valid-user
Allow from 99.88.77.66
Satisfy Any
Cách thức này đảm bảo đặt CHMOD cho các loại file xác định.
# ensure CHMOD settings for specified file types4.16. Ngụy trang tất cả các định dạng mở rộng
# remember to never set CHMOD 777 unless you know what you are doing
# files requiring write access should use CHMOD 766 rather than 777
# keep specific file types private by setting their CHMOD to 400
chmod .htpasswd files 640
chmod .htaccess files 644
chmod php files 600
Ngụy trang tất cả các file và coi như file .php
# diguise all file extensions as phpHoặc như các định dạng khác. Ngoài ra, có thể che giấu file php dưới các định dạng khác:
ForceType application/x-httpd-php
<FilesMatch "\.(htm|html|php)$">4.17. Chống tấn công từ chối dịch vụ bằng cách giới hạn kích thước file upload
SetHandler application/x-httpd-php
</FilesMatch>
# protect against DOS attacks by limiting file upload size4.18. Bảo vệ thư mục bằng cách disable việc thực thi các script
LimitRequestBody 10240000
# secure directory by disabling script execution4.19. Yêu cầu SSL
AddHandler cgi-script .php .pl .py .jsp .asp .htm .shtml .sh .cgi
Options –ExecCGI
# require SSL
SSLOptions +StrictRequire
SSLRequireSSL
SSLRequire %{HTTP_HOST} eq "domain.tld"
ErrorDocument 403 https://domain.tld
# require SSL without mod_ssl5. Một số cấu hình hữu ích khác
RewriteCond %{HTTPS} !=on [NC]
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
5.1. Kiểm tra URL
# automatically corect simple speling erors5.2. Sắp xếp lại trang thông báo lỗi
<IfModule mod_speling.c>
CheckSpelling On
</IfModule>
Cấu hình này rất hữu ích vì nó đưa ra lỗi cho người truy cập website một cách thân thiện, giúp cho chủ website hiện thị các thông báo lỗi theo cách riêng.
# serve custom error pages5.3. Chỉ dẫn cho browser download về máy thay vì chạy trực tiếp
ErrorDocument 400 /errors/400.html
ErrorDocument 401 /errors/401.html
ErrorDocument 403 /errors/403.html
ErrorDocument 404 /errors/404.html
ErrorDocument 500 /errors/500.html
Điều này hữu ích đối với các file multi media
# instruct browser to download multimedia filesCó thể áp dụng với các định dạng khác (Xem thêm phần: 3.9)
AddType application/octet-stream .avi
AddType application/octet-stream .mpg
AddType application/octet-stream .wmv
AddType application/octet-stream .mp3
5.4. Chỉ thị server hiển thị mã nguồn với một số file thực thi
Một số trường hợp cần hiển thị mã nguồn của một file thay vì thực thi chúng, sử dụng:
RemoveHandler cgi-script .pl .py .cgi5.5. Redirect người dùng tới một site tạm thời khi phát triển hoặc sửa lỗi
Trong quá trình phát triển, bảo trì hay sửa chữa website, bạn không muốn khách hàng viếng thăm, cấu hình dưới sẽ giúp chuyển hướng người dùng tới một site khác trong khi quản trị viên vẫn có khả năng truy nhập đầy đủ (x.x.x.x là IP của quản trị):
# redirect all visitors to alternate site but retain full access for you5.6. Chặn truy cập tới file hay thư mục theo thời gian
ErrorDocument 403 http://www.alternate-site.com
Order deny,allow
Deny from all
Allow from x.x.x.x
# prevent access during the midnight hour
RewriteCond %{TIME_HOUR} ^12$
RewriteRule ^.*$ - [F,L]
# prevent access throughout the afternoon6. Thủ thuật redirect
RewriteCond %{TIME_HOUR} ^(12|13|14|15)$
RewriteRule ^.*$ - [F,L]
Đối với tất cả các loại redirect sử dụng mode_rewrite cần enable chế độ: RewriteEngine.
# initialize and enable rewrite engine6.1. Redirect từ http://www.domain.com sang http://domain.com
RewriteEngine on
# permanently redirect from www domain to non-www domain6.2. Redirect từ một domain cũ sang domain mới
RewriteEngine on
Options +FollowSymLinks
RewriteCond %{HTTP_HOST} ^www\.domain\.tld$ [NC]
RewriteRule ^(.*)$ http://domain.tld/$1 [R=301,L]
# redirect from old domain to new domain6.3. Redirect “String Variations” sang một địa chỉ
RewriteEngine On
RewriteRule ^(.*)$ http://www.new-domain.com/$1 [R=301,L]
Giả sử một request có chứa string: “some-string”, ta sẽ chuyển request này tới trang: http://some-string.com
# redirect any variations of a specific character string to a specific addressMột số phương pháp khác:
RewriteRule ^some-string http://www.some-string.com [R]
# map URL variations to the same directory on the same server
AliasMatch ^/director(y|ies) /www/docs/target
# map URL variations to the same directory on a different server6.4. Một số redirect khác
RedirectMatch ^/[dD]irector(y|ies) http://domain.com
Redirect một site đầu vào với trạng thái 301:
# redirect an entire site via 301Redirect một file với trạng thái 301:
redirect 301 / http://www.domain.com/
# redirect a specific file via 301Redirect một site qua một redirect liên tục:
redirect 301 /current/currentfile.html http://www.newdomain.com/new/newfile.html
# redirect an entire site via permanent redirectRedirect một trang hoặc một thư mục với redirect liên tục:
Redirect permanent / http://www.domain.com/
# redirect a page or directoryRedirect một file sử dụng RedirectMatch:
Redirect permanent old_file.html http://www.new-domain.com/new_file.html
Redirect permanent /old_directory/ http://www.new-domain.com/new_directory/
# redirect a file using RedirectMatchKhi redirect các file, sử dụng luật Redirect với các file trong cùng domain, sử dụng luật RewriteRule cho bất cứ domain nào. Luật RewriteRule mạnh hơn luật Redirect.
RedirectMatch 301 ^.*$ http://www.domain.com/index.html
# redirect files directories and domains via RewriteRule6.5. Chuyển khách hàng tới một domain con
RewriteRule http://old-domain.com/old-file.htmlhttp://new-domain.com/new-file.html
RewriteRule http://old-domain.com/old-dir/http://new-domain.com/new-dir/
RewriteRule http://old-domain.com/http://new-domain.com/
Luật này cho phép tất cả các visitor xem page thông qua domain con.
# send visitors to a subdomain6.6. Một số redirect khác
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^subdomain\.domain\.com$ [NC]
RewriteRule ^/(.*)$ http://subdomain.domain.tld/$1 [L,R=301]
# rewrite only if the file is not found
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)special\.html?$ cgi-bin/special/special-html/$1
# rewrite only if an image is not found
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule images/special/(.*).gif cgi-bin/special/mkgif?$1
# seo-friendly rewrite rules for various directories
RewriteRule ^(.*)/aud/(.*)$ $1/audio-files/$2 [L,R=301]
RewriteRule ^(.*)/img/(.*)$ $1/image-files/$2 [L,R=301]
RewriteRule ^(.*)/fla/(.*)$ $1/flash-files/$2 [L,R=301]
RewriteRule ^(.*)/vid/(.*)$ $1/video-files/$2 [L,R=301]
# broswer sniffing via htaccess environmental variables
RewriteCond %{HTTP_USER_AGENT} ^Mozilla.*
RewriteRule ^/$ /index-for-mozilla.html [L]
RewriteCond %{HTTP_USER_AGENT} ^Lynx.*
RewriteRule ^/$ /index-for-lynx.html [L]
RewriteRule ^/$ /index-for-all-others.html [L]
# redirect query to Google search
Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REQUEST_URI} .google\.php*
RewriteRule ^(.*)$ ^http://www.google.com/search?q=$1 [R,NC,L]
# deny request according to the request method
RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK|OPTIONS|HEAD)$ [NC]
RewriteRule ^.*$ - [F]
# redirect uploads to a better place
RewriteCond %{REQUEST_METHOD} ^(PUT|POST)$ [NC]
RewriteRule ^(.*)$ /cgi-bin/upload-processor.cgi?p=$1 [L,QSA]
# seo friendly redirect for a single file
Redirect 301 /old-dir/old-file.html http://domain.com/new-dir/new-file.html
# seo friendly redirect for multiple files
# redirects all files in dir directory with first letters xyz
RedirectMatch 301 /dir/xyz(.*) http://domain.com/$1
# seo friendly redirect entire site to a different domain7. Một số cấu hình khác
Redirect 301 / http://different-domain.com
7.1. Kích hoạt SSI
Khi sử dụng chế độ SSI, phần mở rộng các file trên server phải ở dạng .shtml thay vì .html. Điều này gây bất lợi cho các website đã thiết lập dạng .html, để tránh phải chuyển đổi lại định dạng mở rộng file trên server, tạo file .htaccess với nội dung:
AddHandler server-parsed .htmlCó thể thêm nhiều dòng để server chấp nhận nhiều định dạng khác nhau.
Ví dụ:
AddHandler server-parsed .html
AddHandler server-parsed .shtml
AddHandler server-parsed .htm
7.2. Chặn truy cập tới các file include trong file .php
Để tránh bị truy cập tới thư mục chứa các file .php, tạo file .htaccess với nội dung:
## Enable Mod Rewrite, this is only required once in each .htaccess file
RewriteEngine On
RewriteBase /
## Test for access to includes directory
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /includes/ .*$ [NC]
## Test that file requested has php extension
RewriteCond %{REQUEST_FILENAME} ^.+\.php$
## Forbid Access
RewriteRule .* - [F,NS,L]
Trong đó, includes là thư mục chứa file .php