Một số cấu hình trên file htaccess



tải về 150.57 Kb.
Chuyển đổi dữ liệu10.05.2018
Kích150.57 Kb.
#38116

Một số cấu hình trên file .htaccess




  1. 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/.htpasswd 
AuthType Basic 
require valid-user 
ErrorDocument 401 /error_pages/401.html 
AddHandler server-parsed .html


Ví 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 rewriting
RewriteEngine on
2.2. Enable Symbolic links

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 links
Options +FollowSymLinks
2.3. Enable AllowOverride

Đố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 privileges

AllowOverride Options 



2.4. Đặt tên lại file .htaccess

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 files
AccessFileName ht.access
Khi 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):

# protect renamed htaccess files

Order deny,allow 
Deny from all 

2.5. Giữ lại các luật đã được định nghĩa trong httpd.conf

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 Inherit
3. 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 allowoverride
AllowOverride None
3.2. Tăng hiệu năng bằng cách truyền tập các ký tự

# pass the default character set


AddDefaultCharset utf-8
3.3. Tăng hiệu năng bởi việc bảo vệ bandwidth

# preserve bandwidth for PHP enabled servers

php_value zlib.output_compression 16386 

3.4. Disable chữ ký server

# disable the server signature


ServerSignature Off
3.5. Cài đặt server timezone

# set the server timezone


SetEnv TZ America/Washington
3.6. Đặt địa chỉ email cho quản trị server

# set the server administrator email


SetEnv SERVER_ADMIN default@domain.com 


3.7. Tăng tốc độ duyệt site bằng việc enable file caching

# cache images and flash content for one month

Header set Cache-Control "max-age=2592000" 

# cache text, css, and javascript files for one week

Header set Cache-Control "max-age=604800" 

# cache html and htm files for one day

Header set Cache-Control "max-age=43200" 

# implement minimal caching during site development

Header set Cache-Control "max-age=5" 

# explicitly disable caching for scripts and other dynamic files

Header unset Cache-Control 

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

ExpiresActive Off 





    • Convert common time intervals into seconds:

    • 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



3.8. Cài đặt ngôn ngữ và kiểu mã hóa mặc định

# set the default language


DefaultLanguage en-US 
# set the default character set
AddDefaultCharset UTF-8


3.9. Mô tả MIME

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 swf 
AddType application/x-shockwave-flash .swf
AddType video/x-flv .flv
AddType image/x-icon .ico
Mộ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

Danh sách các MIME và loại file tương ứng:

AddType text/html .html .htm 
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




3.10. Gửi kiểu mã hóa và header không cần thẻ meta

# send the language tag and default character set


# AddType 'text/html; charset=UTF-8' html
AddDefaultCharset UTF-8
DefaultLanguage en-US
3.11. Giới hạn các request GET và PUT

# limit server request methods to GET and PUT


Options -ExecCGI -Indexes -All
RewriteEngine on
RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK|OPTIONS|HEAD) RewriteRule .* - [F]
3.12. Lựa chọn file xử lý theo phương thức request tới server

# process files according to server request method


Script PUT /cgi-bin/upload.cgi
Script GET /cgi-bin/download.cgi
3.13. Thực thi một định dạng file bằng 1 cgi script

# execute all png files via png-script.cgi


Action image/png /cgi-bin/png-script.cgi

  


  1. 03/07/13, 05:18 PM #2

mask 

Junior Member

 

Ngày tham gia



08:53 AM

Bài viết


10

Cảm ơn


0

Được Cảm ơn 2 lần trong 2 Bài viết



4. Các cấu hình bảo mật

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 file

order allow,deny 


deny from all 

4.2. Ngăn cản truy cập tới một file đặc biệt

Để 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 file

order allow,deny 


deny from all 

4.3. Chặn truy cập tới nhiều file

Order Allow,Deny 


Deny from all 

4.4. Chống browse thư mục trái phép

Đả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 browsing
Options All –Indexes
Ngược lại để cho phép người dùng có thể xem dưới dạng này, sử dụng:

# enable directory browsing


Options All +Indexes
Ngăn cản server listing directory:

# prevent folder listing


IndexIgnore *
Ngăn cản truy nhập vào các file có định dạng nào đó, sử dụng IndexIgnore

# prevent display of select file types


IndexIgnore *.wmv *.mp4 *.avi *.etc
4.5. Thay đổi trang index mặc định

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 page
DirectoryIndex business.html
Hoặ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

# serve first available alternate default index page from series


DirectoryIndex filename.html index.cgi index.pl default.htm
4.6. Ngụy trang cho định dạng script

Để 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 files
AddType application/x-httpd-php .foo

# serve foo files as cgi files


AddType application/x-httpd-cgi .foo
4.7. Giới hạn truy cập tới mạng LAN

# limit access to local area network

order deny,allow 
deny from all 
allow from 192.168.0.0/33 

4.8. Bảo vệ thư mục bằng địa chỉ IP và/hoặc domain

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 here

order allow,deny 


allow from all 
deny from x.y.z.v 
deny from .*domain\.com.* 

Ngượ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

# deny all except those indicated here

order deny,allow 


deny from all 
allow from x.y.z.v 
allow from .*domain\.com.*

Ngoà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)

# block visitors referred from indicated domains

RewriteEngine on 


RewriteCond %{HTTP_REFERER} abc\.com [NC,OR] 
RewriteCond %{HTTP_REFERER} xyz\.com [NC,OR] 
RewriteRule .* - [F] 

4.9. Ngăn cản hoặc cho phép truy cập domain theo dải địa chỉ IP

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

order allow,deny 


allow from all 
deny from 10.1.0.0/16 
deny from 80.0.0/8 

Để cho phép bởi CIDR:

# allow IP range by CIDR number

order deny,allow 


deny from all 
allow from 10.1.0.0/16 
allow from 80.0.0/8 

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

# block IP range by address truncation

order allow,deny 


allow from all 
deny from 99.88.77.66 
deny from 99.88.77.* 
deny from 99.88.*.* 
deny from 99.*.*.* 

Cho phép địa chỉ IP theo cách này:

# allow IP range by address truncation

order deny,allow 


deny from all 
allow from 99.88.77.66 
allow from 99.88.77.* 
allow from 99.88.*.* 
allow from 99.*.*.* 

4.10. Chặn hoặc cho phép nhiều địa chỉ trong cùng 1 dòng

Block:


# block two unique IP addresses
deny from 99.88.77.66 11.22.33.44
# block three ranges of IP addresses
deny from 99.88 99.88.77 11.22.33
Allow:

# allow two unique IP addresses


allow from 99.88.77.66 11.22.33.44
# allow three ranges of IP addresses
allow from 99.88 99.88.77 11.22.33
4.11. Các luật khác sử dụng để block hay allow địa chỉ IP

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


order deny,allow
deny from domain.com
allow from sub.domain.com
4.12. Ngừng các hotlinking, luân chuyển nội dung server

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

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]

Để 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:

# serve a standard 403 forbidden error page
RewriteRule .*\.(gif|jpg)$ - [F,L]
Để 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:

# allow linking from the following site


RewriteCond %{HTTP_REFERER} !^http://(www\.)?goodsite\.com/.*$ [NC]
4.13. Chặn Evil Robots, Site Rippers, và Offline Browsers

RewriteEngine On
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]

Thay vì gửi một thông báo thân thiện, có thể gửi lại mộ website:

# send em to a hellish website of your choice
RewriteRule ^.*$ http://www.hellish-website.com [R,L]
Hoặc gửi một blackhold fake email:

# send em to a virtual blackhole of fake email addresses


RewriteRule ^.*$ http://english-61925045732.spampoison.com [R,L]
Có thể chặn theo referrer, ở đây ta chặn iaea.org:

RewriteCond %{HTTP_REFERER} ^http://www.iaea.org$


RewriteRule !^http://[^/.]\.yourdomain\.com.* - [F,L]
Một số cách chặn khác:

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


RewriteCond %{REMOTE_ADDR} 192.168.10.*
RewriteRule .* http://www.differentspamsite.com/index.html [R]
4.14. Pass bảo vệ

Đặ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_smithCF9Pam/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

AuthType Basic 
AuthName "Prompt" 
AuthUserFile /home/path/.htpasswd 
Require valid-user 

# password-protect multiple files

AuthType basic 
AuthName "Development" 
AuthUserFile /home/path/.htpasswd 
Require valid-user 

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


# 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
4.15. Tự động đặt CHMOD cho các loại file

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 types
# 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
4.16. Ngụy trang tất cả các định dạng mở rộng

Ngụy trang tất cả các file và coi như file .php

# diguise all file extensions as php
ForceType application/x-httpd-php
Hoặ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:
SetHandler application/x-httpd-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

# protect against DOS attacks by limiting file upload size


LimitRequestBody 10240000
4.18. Bảo vệ thư mục bằng cách disable việc thực thi các script

# secure directory by disabling script execution


AddHandler cgi-script .php .pl .py .jsp .asp .htm .shtml .sh .cgi
Options –ExecCGI
4.19. Yêu cầu SSL

# require SSL


SSLOptions +StrictRequire
SSLRequireSSL
SSLRequire %{HTTP_HOST} eq "domain.tld"
ErrorDocument 403 https://domain.tld

# require SSL without mod_ssl


RewriteCond %{HTTPS} !=on [NC]
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
5. Một số cấu hình hữu ích khác

5.1. Kiểm tra URL

# automatically corect simple speling erors

CheckSpelling On 

5.2. Sắp xếp lại trang thông báo lỗi

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 pages
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
5.3. Chỉ dẫn cho browser download về máy thay vì chạy trực tiếp

Điều này hữu ích đối với các file multi media

# instruct browser to download multimedia files
AddType application/octet-stream .avi
AddType application/octet-stream .mpg
AddType application/octet-stream .wmv
AddType application/octet-stream .mp3
Có thể áp dụng với các định dạng khác (Xem thêm phần: 3.9)
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 .cgi

5.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 you
ErrorDocument 403 http://www.alternate-site.com
Order deny,allow
Deny from all
Allow from x.x.x.x
5.6. Chặn truy cập tới file hay thư mục theo thời gian

# prevent access during the midnight hour


RewriteCond %{TIME_HOUR} ^12$
RewriteRule ^.*$ - [F,L]

# prevent access throughout the afternoon


RewriteCond %{TIME_HOUR} ^(12|13|14|15)$
RewriteRule ^.*$ - [F,L]

 

6. Thủ thuật redirect

Đố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 engine


RewriteEngine on
6.1. Redirect từ http://www.domain.com sang http://domain.com

# permanently redirect from www domain to non-www domain


RewriteEngine on
Options +FollowSymLinks
RewriteCond %{HTTP_HOST} ^www\.domain\.tld$ [NC]
RewriteRule ^(.*)$ http://domain.tld/$1 [R=301,L]
6.2. Redirect từ một domain cũ sang domain mới

# redirect from old domain to new domain


RewriteEngine On
RewriteRule ^(.*)$ http://www.new-domain.com/$1 [R=301,L]
6.3. Redirect “String Variations” sang một địa chỉ

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 address
RewriteRule ^some-string http://www.some-string.com [R]
Một số phương pháp khác:

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


RedirectMatch ^/[dD]irector(y|ies) http://domain.com
6.4. Một số redirect khác

Redirect một site đầu vào với trạng thái 301:

# redirect an entire site via 301
redirect 301 / http://www.domain.com/
Redirect một file với trạng thái 301:

# redirect a specific file via 301


redirect 301 /current/currentfile.html http://www.newdomain.com/new/newfile.html
Redirect một site qua một redirect liên tục:

# redirect an entire site via permanent redirect


Redirect permanent / http://www.domain.com/
Redirect một trang hoặc một thư mục với redirect liên tục:

# redirect a page or directory


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 một file sử dụng RedirectMatch:

# redirect a file using RedirectMatch


RedirectMatch 301 ^.*$ http://www.domain.com/index.html
Khi 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.

# redirect files directories and domains via RewriteRule


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/
6.5. Chuyển khách hàng tới một domain con

Luật này cho phép tất cả các visitor xem page thông qua domain con.

# send visitors to a subdomain
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^subdomain\.domain\.com$ [NC]
RewriteRule ^/(.*)$ http://subdomain.domain.tld/$1 [L,R=301]
6.6. Một số redirect khác


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


Redirect 301 / http://different-domain.com
7. Một số cấu hình khác

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

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

tải về 150.57 Kb.

Chia sẻ với bạn bè của bạn:




Cơ sở dữ liệu được bảo vệ bởi bản quyền ©hocday.com 2024
được sử dụng cho việc quản lý

    Quê hương