Bên dưới là các đoạn .htaccess rất thông dụng trong quá trình xây dựng các website sử dụng PHP & Linux.

Bỏ www trong url

Đôi khi vì mục đích SEO bạn muốn bỏ www trong tất cả các url:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^your-site.com$ [NC]
RewriteRule ^(.*)$ http://your-site.com/$1 [L,R=301]

Chặn hotlinking

Bảo vệ hình ảnh trong website khỏi những kẻ ăn cắp traffic dùng link hình trực tiếp từ website của bạn:

RewriteEngine On
#Replace ?mysite\.com/ with your blog url
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?mysite\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
#Replace /images/nohotlink.jpg with your "don't hotlink" image url
RewriteRule .*\.(jpe?g|gif|bmp|png)$ /images/nohotlink.jpg [L]

Redirect WordPress feed sang feedburner

Nếu bạn dùng WP & feedburner:

<IfModule mod_alias.c>
RedirectMatch 301 /feed/?$ http://feeds.feedburner.com/yourfeed
</IfModule>

Tạo trang báo lỗi

Tự tạo những trang báo lỗi 404, 401, 500….

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

Buộc download một loại file nào đó

Nếu website của bạn có các các file như .xls, .pdf, .mp3 và bạn muốn người xem luôn luôn phải download những file này theo vì có thể nghe/xem online:

<Files *.xls>
ForceType application/octet-stream
Header set Content-Disposition attachment
</Files>
<Files *.eps>
ForceType application/octet-stream
Header set Content-Disposition attachment
</Files>

Ghi log lỗi PHP

Rất hữu dụng cho việc hoàn thiện website và ngăn chặn hack. Đoạn code sau sẽ tạo file php_error.log trên server để ghi lại các lỗi PHP trong quá trình hoạt động:

# display no errs to user
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
# log to file
php_flag log_errors on
php_value error_log /location/to/php_error.log

Bỏ phần extensions của file trong url

Nếu bạn muốn bỏ các đuôi .html, .php, .aspx,… khỏi url:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html
# Replace html with your file extension, eg: php, htm, asp

Ngăn chặn hiển thị danh sách file trong thư mục

Bạn không muốn người xem có thể xem danh sách file & thư mục con của 1 thư mục dùng để  lưu trữ như images, download, upload,..:

Options -Indexes

Nén dữ liệu tĩnh

Dùng để tăng tốc website & tiết kiệm bandwidth:

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

Tự động thêm utf-8 charset vào tất cả các file

Đảm bảo website luôn luôn được mã hóa chính xác:

<FilesMatch "\.(htm|html|css|js)$">
AddDefaultCharset UTF-8
</FilesMatch>