Kumpulan Htaccess Snippets Yang Dapat Memudahkanmu
Note
File .htaccess diperuntukkan untuk user yang tidak memiliki hak untuk mengedit file konfigurasi server utama. Mereka secara intrinsik lebih lambat dan lebih rumit daripada menggunakan konfigurasi utama. Silakan lihat caranya di dokumentasi httpd untuk detail lebih lanjut.
Disclaimer
Meskipun memasukkan snippets ke file .htaccess sebagian besar kode sudah cukup, ada beberapa kasus di mana modifikasi tertentu mungkin diperlukan. Gunakan dengan resiko sendiri.
Penting
Apache 2.4 telah memperkenalkan beberapa perubahan, terutama dalam konfigurasi kontrol akses. Untuk informasi lebih lanjut, periksa dokumen pemutakhiran serta isu ini.
Credit
Apa yang saya berikan di sini sebagian besar mengumpulkan snippet yang berguna dari seluruh interweb (misalnya, sebagian besar berasal dari Apache Server Configs) ke satu tempat. Meskipun saya telah mencoba untuk memberikan credit pada waktu lalu, ada beberapa hal yang mungkin tidak bisa.
Table of Contents
- Rewrite and Redirection
- Security
- Deny All Access
- Deny All Access Except Yours
- Allow All Access Except Spammers'
- Deny Access to Hidden Files and Directories
- Deny Access to Backup and Source Files
- Disable Directory Browsing
- Disable Image Hotlinking
- Disable Image Hotlinking for Specific Domains
- Password Protect a Directory
- Password Protect a File or Several Files
- Block Visitors by Referrer
- Prevent Framing the Site
- Performance
- Miscellaneous
Rewrite and Redirection
Note: DIharuskan bahwa kamu memiliki mod_rewrite
installed and enabled.
Force www
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]
Force www in a Generic Way
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
This works for any domain. Source
Force non-www
Masih diperdebatkan apakah www atau non-www adalah cara yang baik, jadi jika kamu adalah menyukai domain kosong, kode
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]
Force non-www in a Generic Way
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|off
RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$
RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L]
Force HTTPS
RewriteEngine on
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
# Note: It’s also recommended to enable HTTP Strict Transport Security (HSTS)
# on your HTTPS website to help prevent man-in-the-middle attacks.
# See https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security
<IfModule mod_headers.c>
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
</IfModule>
Force HTTPS Behind a Proxy
Berguna jika kamu memiliki proxy pada server kamu yang melakukan penghentian TLS.
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
Force Trailing Slash
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]
Remove Trailing Slash
Snippets ini akan menghapus jalur yang diakhiri dengan garis miring (kecuali untuk direktori sebenarnya),
e.g. http://www.example.com/blog/
menjadi http://www.example.com/blog
. Ini cukup penting untuk SEO, karena direkomendasikan untuk memiliki URL canonical untuk setiap halaman.
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=301,L]
Redirect a Single Page
Redirect 301 /oldpage.html http://www.example.com/newpage.html
Redirect 301 /oldpage2.html http://www.example.com/folder/
Redirect Using RedirectMatch
RedirectMatch 301 /subdirectory(.*) http://www.newsite.com/newfolder/$1
RedirectMatch 301 ^/(.*).htm$ /$1.html
RedirectMatch 301 ^/200([0-9])/([^01])(.*)$ /$2$3
RedirectMatch 301 ^/category/(.*)$ /$1
RedirectMatch 301 ^/(.*)/htaccesselite-ultimate-htaccess-article.html(.*) /htaccess/htaccess.html
RedirectMatch 301 ^/(.*).html/1/(.*) /$1.html$2
RedirectMatch 301 ^/manual/(.*)$ http://www.php.net/manual/$1
RedirectMatch 301 ^/dreamweaver/(.*)$ /tools/$1
RedirectMatch 301 ^/z/(.*)$ http://static.askapache.com/$1
Alias a Single Directory
RewriteEngine On
RewriteRule ^source-directory/(.*) /target-directory/$1 [R=301,L]
Alias Paths To Script
FallbackResource /index.fcgi
Contoh ini memiliki index.fcgi
file di beberapa direktori, dan permintaan apa pun dalam direktori itu yang gagal menyelesaikan nama file/direktori akan dikirim ke index.fcgi
naskah. Itu bagus jika kamu mau baz.foo/some/cool/path
untuk diganti oleh baz.foo/index.fcgi
(yang juga mendukung permintaan untuk baz.foo
) sambil mempertahankan baz.foo/css/style.css
dan sejenisnya. Dapatkan akses ke jalur asli dari variabel environment PATH_INFO, seperti yang diekspos ke script environment kamu.
RewriteEngine On
RewriteRule ^$ index.fcgi/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L]
Ini adalah versi arahan FallbackResource yang kurang efisien (karena menggunakan mod_rewrite
lebih kompleks daripada hanya menangani FallbackResource
direktif), tetapi juga lebih fleksibel.
Redirect an Entire Site
Redirect 301 / http://newsite.com/
This way does it with links intact. That is www.oldsite.com/some/crazy/link.html
will become www.newsite.com/some/crazy/link.html
. This is extremely helpful when you are just “moving” a site to a new domain. Source
Alias “Clean” URLs
Cuplikan ini memungkinkan Anda menggunakan URL "clean" -- URL tanpa ekstensi PHP, mis. example.com/users
dari example.com/users.php
.
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]
Security
Deny All Access
## Apache 2.2
Deny from all
## Apache 2.4
# Require all denied
Tapi tunggu, ini juga akan mengunci Anda dari konten Anda! Dengan demikian memperkenalkan...
Deny All Access Except Yours
## Apache 2.2
Order deny,allow
Deny from all
Allow from xxx.xxx.xxx.xxx
## Apache 2.4
# Require all denied
# Require ip xxx.xxx.xxx.xxx
xxx.xxx.xxx.xxx
adalah IP Anda. Jika Anda mengganti tiga digit terakhir dengan 0/12 misalnya, ini akan menentukan rentang IP dalam jaringan yang sama, sehingga Anda tidak akan kesulitan untuk mendaftar semua IP yang diizinkan secara terpisah. Source
Sekarang tentu saja ada versi terbalik:
Allow All Access Except Spammers'
## Apache 2.2
Order deny,allow
Deny from xxx.xxx.xxx.xxx
Deny from xxx.xxx.xxx.xxy
## Apache 2.4
# Require all granted
# Require not ip xxx.xxx.xxx.xxx
# Require not ip xxx.xxx.xxx.xxy
Deny Access to Hidden Files and Directories
File dan direktori tersembunyi (yang namanya dimulai dengan titik .) harus sebagian besar, jika tidak semua, diamankan. Sebagai contoh: .htaccess, .htpasswd, .git, .hg...
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule "(^|/)\." - [F]
Atau, Anda bisa memunculkan kesalahan "Tidak Ditemukan", tanpa memberi petunjuk kepada penyerang:
RedirectMatch 404 /\..*$
Deny Access to Backup and Source Files
File-file ini mungkin ditinggalkan oleh beberapa editor teks/HTML (seperti Vi/Vim) dan menimbulkan bahaya keamanan yang besar jika diekspos ke publik.
<FilesMatch "(\.(bak|config|dist|fla|inc|ini|log|psd|sh|sql|swp)|~)$">
## Apache 2.2
Order allow,deny
Deny from all
Satisfy All
## Apache 2.4
# Require all denied
</FilesMatch>
Disable Directory Browsing
Options All -Indexes
Disable Image Hotlinking
RewriteEngine on
# Remove the following line if you want to block blank referrer too
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(.+\.)?example.com [NC]
RewriteRule \.(jpe?g|png|gif|bmp)$ - [NC,F,L]
# If you want to display a “blocked” banner in place of the hotlinked image,
# replace the above rule with:
# RewriteRule \.(jpe?g|png|gif|bmp) http://example.com/blocked.png [R,L]
Disable Image Hotlinking for Specific Domains
Terkadang kamu ingin menonaktifkan hotlinking gambar dari beberapa orang jahat saja.
RewriteEngine on
RewriteCond %{HTTP_REFERER} ^https?://(.+\.)?badsite\.com [NC,OR]
RewriteCond %{HTTP_REFERER} ^https?://(.+\.)?badsite2\.com [NC,OR]
RewriteRule \.(jpe?g|png|gif|bmp)$ - [NC,F,L]
# If you want to display a “blocked” banner in place of the hotlinked image,
# replace the above rule with:
# RewriteRule \.(jpe?g|png|gif|bmp) http://example.com/blocked.png [R,L]
Password Protect a Directory
First you need to create a .htpasswd
file somewhere in the system:
htpasswd -c /home/fellowship/.htpasswd boromir
Then you can use it for authentication:
AuthType Basic
AuthName "One does not simply"
AuthUserFile /home/fellowship/.htpasswd
Require valid-user
Password Protect a File or Several Files
AuthName "One still does not simply"
AuthType Basic
AuthUserFile /home/fellowship/.htpasswd
<Files "one-ring.o">
Require valid-user
</Files>
<FilesMatch ^((one|two|three)-rings?\.o)$>
Require valid-user
</FilesMatch>
Block Visitors by Referrer
Ini menolak akses untuk semua pengguna yang berasal dari (dirujuk oleh) domain tertentu. Source
RewriteEngine on
# Options +FollowSymlinks
RewriteCond %{HTTP_REFERER} somedomain\.com [NC,OR]
RewriteCond %{HTTP_REFERER} anotherdomain\.com
RewriteRule .* - [F]
Prevent Framing the Site
This mencegah situs web untuk dibingkai (yaitu dimasukkan ke dalam iframe
tag), ketika masih memungkinkan pembingkaian untuk URI tertentu.
SetEnvIf Request_URI "/starry-night" allow_framing=true
Header set X-Frame-Options SAMEORIGIN env=!allow_framing
Performance
Compress Text Files
<IfModule mod_deflate.c>
# Force compression for mangled headers.
# https://developer.yahoo.com/blogs/ydn/pushing-beyond-gzipping-25601.html
<IfModule mod_setenvif.c>
<IfModule mod_headers.c>
SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
</IfModule>
</IfModule>
# Compress all output labeled with one of the following MIME-types
# (for Apache versions below 2.3.7, you don't need to enable `mod_filter`
# and can remove the `<IfModule mod_filter.c>` and `</IfModule>` lines
# as `AddOutputFilterByType` is still in the core directives).
<IfModule mod_filter.c>
AddOutputFilterByType DEFLATE application/atom+xml \
application/javascript \
application/json \
application/rss+xml \
application/vnd.ms-fontobject \
application/x-font-ttf \
application/x-web-app-manifest+json \
application/xhtml+xml \
application/xml \
font/opentype \
image/svg+xml \
image/x-icon \
text/css \
text/html \
text/plain \
text/x-component \
text/xml
</IfModule>
</IfModule>
Set Expires Headers
Header kedaluwarsa memberi tahu browser apakah mereka harus meminta file tertentu dari server atau hanya mengambilnya dari cache. Dianjurkan untuk mengatur header kedaluwarsa konten statis ke sesuatu yang jauh di masa depan.
Jika Anda tidak mengontrol pembuatan versi dengan penghilang cache berbasis nama file, pertimbangkan untuk menurunkan waktu cache untuk sumber daya seperti CSS dan JS menjadi sekitar 1 minggu.
<IfModule mod_expires.c>
ExpiresActive on
ExpiresDefault "access plus 1 month"
# CSS
ExpiresByType text/css "access plus 1 year"
# Data interchange
ExpiresByType application/json "access plus 0 seconds"
ExpiresByType application/xml "access plus 0 seconds"
ExpiresByType text/xml "access plus 0 seconds"
# Favicon (cannot be renamed!)
ExpiresByType image/x-icon "access plus 1 week"
# HTML components (HTCs)
ExpiresByType text/x-component "access plus 1 month"
# HTML
ExpiresByType text/html "access plus 0 seconds"
# JavaScript
ExpiresByType application/javascript "access plus 1 year"
# Manifest files
ExpiresByType application/x-web-app-manifest+json "access plus 0 seconds"
ExpiresByType text/cache-manifest "access plus 0 seconds"
# Media
ExpiresByType audio/ogg "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType video/mp4 "access plus 1 month"
ExpiresByType video/ogg "access plus 1 month"
ExpiresByType video/webm "access plus 1 month"
# Web feeds
ExpiresByType application/atom+xml "access plus 1 hour"
ExpiresByType application/rss+xml "access plus 1 hour"
# Web fonts
ExpiresByType application/font-woff2 "access plus 1 month"
ExpiresByType application/font-woff "access plus 1 month"
ExpiresByType application/vnd.ms-fontobject "access plus 1 month"
ExpiresByType application/x-font-ttf "access plus 1 month"
ExpiresByType font/opentype "access plus 1 month"
ExpiresByType image/svg+xml "access plus 1 month"
</IfModule>
Turn eTags Off
Dengan menghapus header ETag, Kamu bisa menonaktifkan cache dan browser agar tidak dapat memvalidasi file, sehingga mereka terpaksa mengandalkan header Cache-Control dan Expires kamu.
<IfModule mod_headers.c>
Header unset ETag
</IfModule>
FileETag None
Miscellaneous
Set PHP Variables
php_value <key> <val>
# For example:
php_value upload_max_filesize 50M
php_value max_execution_time 240
Custom Error Pages
ErrorDocument 500 "Houston, we have a problem."
ErrorDocument 401 http://error.example.com/mordor.html
ErrorDocument 404 /errors/halflife3.html
Force Downloading
Terkadang Anda ingin memaksa browser mengunduh beberapa konten alih-alih menampilkannya.
<Files *.md>
ForceType application/octet-stream
Header set Content-Disposition attachment
</Files>
Now there is a yang to this yin:
Prevent Downloading
Terkadang kamu ingin memaksa browser untuk menampilkan beberapa konten alih-alih mengunduhnya.
<FilesMatch "\.(tex|log|aux)$">
Header set Content-Type text/plain
</FilesMatch>
Allow Cross-Domain Fonts
Webfont yang dilayani CDN mungkin tidak berfungsi di Firefox atau IE karena CORS. Snippets ini memecahkan masalah.
<IfModule mod_headers.c>
<FilesMatch "\.(eot|otf|ttc|ttf|woff|woff2)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>
Auto UTF-8 Encode
Konten teks Anda harus selalu dikodekan UTF-8, bukan?
# Use UTF-8 encoding for anything served text/plain or text/html
AddDefaultCharset utf-8
# Force UTF-8 for a number of file formats
AddCharset utf-8 .atom .css .js .json .rss .vtt .xml
Switch to Another PHP Version
Jika Anda menggunakan host bersama, kemungkinan ada lebih dari satu versi PHP yang diinstal, dan terkadang Anda menginginkan versi tertentu untuk situs web Anda. Cuplikan berikut harus mengganti versi PHP untuk Anda.
AddHandler application/x-httpd-php56 .php
# Alternatively, you can use AddType
AddType application/x-httpd-php56 .php
Disable Internet Explorer Compatibility View
Tampilan Kompatibilitas di IE dapat memengaruhi cara beberapa situs web ditampilkan. Cuplikan berikut harus memaksa IE untuk menggunakan Edge Rendering Engine dan menonaktifkan Tampilan Kompatibilitas.
<IfModule mod_headers.c>
BrowserMatch MSIE is-msie
Header set X-UA-Compatible IE=edge env=is-msie
</IfModule>
Serve WebP Images
Jika gambar WebP didukung dan gambar dengan ekstensi .webp dan nama yang sama ditemukan di tempat yang sama dengan gambar jpg/png yang akan ditayangkan, maka gambar WebP akan disajikan sebagai gantinya.
RewriteEngine On
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{DOCUMENT_ROOT}/$1.webp -f
RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1]
Cukup sekian artikel kali ini terima kasih telah berkunjung nantikan update artikel selanjutnya.
Posting Komentar
image quote pre code