Re-and redirect
Note: The server installation and the Enable module are required first mod_rewrite
.
Mandatory www
Rewriteengine Onrewritecond%{http_host} ^example\.com [Nc]rewriterule ^ (. *) $ http://www.example.com/$1 [L,R=301,NC]
Mandatory WWW Universal method
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 method can be used in any Web site. Source
Mandatory NON-WWW
is www good, or non-www good, no conclusion, if you like not with WWW, you can use the following script:
Rewriteengine Onrewritecond%{http_host} ^www\.example\.com [Nc]rewriterule ^ (. *) $ http://example.com/$1 [L,R=301]
Mandatory Non-www General Method
Rewriteengine Onrewritecond%{http_host} ^www\. Rewritecond%{https}s ^on (s) |offrewritecond http%1://%{http_host} ^ (https?:/ /) (www\.)? (. +) $RewriteRule ^%1%3%{request_uri} [R=301,l]
Force HTTPS
Rewriteengine Onrewritecond%{https}!onrewriterule (. *) 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 Atta cks.# 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>
Forcing HTTPS through the proxy
This method is useful for you if you use a proxy.
Rewritecond%{http:x-forwarded-proto}!httpsrewriterule (. *) Https://%{http_host}%{request_uri}
Force add trailing slash
Rewritecond%{request_uri}/+[^\.] + $RewriteRule ^ (. +[^/]) $%{request_uri}/[r=301,l]
Take out the trailing slash
Rewritecond%{request_filename}!-drewriterule ^ (. *)/$/$1 [r=301,l]
Redirect to a page
Redirect 301/oldpage.html http://www.example.com/newpage.htmlRedirect 301/oldpage2.html http://www.example.com/folder/
Source
Directory aliases
Rewriteengine onrewriterule ^source-directory/(. *) target-directory/$1
Script aliases
fallbackresource/index.fcgi
This example have index.fcgi
a file in some directory, and any requests within the that directory that is fail to resolve a filename/d Irectory'll is sent to the index.fcgi
script. It ' s good if you want to being baz.foo/some/cool/path
handled by baz.foo/index.fcgi
(which also supports requests to baz.foo
) while maintaining baz.foo/css/style.css
and the Like. Get access to the original path from the PATH_INFO environment variable, as exposed to your scripting environment.
Rewriteengine onrewriterule ^$ index.fcgi/[Qsa,l]rewritecond%{request_filename}!-frewritecond%{REQUEST_FILENAME}! -drewriterule ^ (. *) $ index.fcgi/$1 [qsa,l]
This was a less efficient version of the Fallbackresource directive (because using was more complex than just handling mod_rewrite
FallbackResource
the directive), but it's also more flexible.
REDIRECT Entire site
Redirect 301/http://newsite.com/
This is the does it with links intact. That's is would www.oldsite.com/some/crazy/link.html
become www.newsite.com/some/crazy/link.html
. This was extremely helpful when you were just "moving" a site to a new domain. Source
A clean URL
This snippet lets the "clean" urls-those without a PHP extension, e.g. example.com/users
instead. example.com/users.php
Rewriteengine Onrewritecond%{script_filename}!-drewriterule ^ ([^.] +) $ $1.php [nc,l]
Source
Security denies all access
# # Apache 2.2Deny from all## Apache 2.4# Require all denied
But wait, this would lock you out from your content as well! Thus Introducing ...
Deny all access (exclude part)
# # Apache 2.2Order Deny,allowdeny from Allallow to xxx.xxx.xxx.xxx## Apache 2.4# Require all denied# Require IP xxx.xxx. Xxx.xxx
xxx.xxx.xxx.xxx
Is your IP. If you replace the last three digits with 0/12 For example, this would specify a range of IPs within the same network, thus Saving the trouble to list all allowed IPs separately. Source
Now of course there ' s a reversed version:
Block Crawler/Rogue Access
# # Apache 2.2Order deny,allowallow from Alldeny from Xxx.xxx.xxx.xxxDeny to xxx.xxx.xxx.xxy## Apache 2.4# Require all GR anted# Require not IP xxx.xxx.xxx.xxx# Require not IP xxx.xxx.xxx.xxy
Protect hidden files and directories
Hidden files and directories (those whose names start with a dot .
) should most, if not all, of the time be secured. F or example: .htaccess
,,, .htpasswd
.git
.hg
.....
Rewritecond%{script_filename}-D [Or]rewritecond%{script_filename}-frewriterule "(^|/) \."-[F]
Alternatively, you can just raise a Not Found
error, giving the attacker dude no clue:
Redirectmatch 404/\. *$
Protect backup files and source code files
These files May is left by some text/html editors (like Vi/vim) and pose a great security danger if exposed to public.
<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>
Source
Prohibit Directory browsing
Options all-indexes
Disable Picture hotlinking
Rewriteengine on# Remove The following line if you want to block blank referrer Toorewritecond%{http_referer}!^ $RewriteC Ond%{http_referer}!^http (s)?:/ /(.+\.)? example.com [Nc]rewriterule \. (jpg|jpeg|png|gif|bmp) $-[nc,f,l]# If you want to display a ' blocked ' banner in place of the hotlinked image, # replace T He above rule with:# rewriterule \. (jpg|jpeg|png|gif|bmp) http://example.com/blocked.png [r,l]
Disable picture hotlinking (specify domain name)
Sometimes want to prohibit picture hotlinking from some bad guys only.
Rewriteengine Onrewritecond%{http_referer} ^http (s)?:/ /(.+\.)? badsite\.com [Nc,or]rewritecond%{http_referer} ^http (s)?:/ /(.+\.)? badsite2\.com [Nc,or]rewriterule \. (jpg|jpeg|png|gif) $-[nc,f,l]# If you want to display a ' blocked ' banner in place of the hotlinked image, # Replace the A Bove rule with:# rewriterule \. (jpg|jpeg|png|gif|bmp) http://example.com/blocked.png [r,l]
Password protected Directory
First need to create a .htpasswd
file somewhere in the system:
Htpasswd-c/home/fellowship/.htpasswd Boromir
Then you can use it for authentication:
AuthType Basicauthname "One does not simply" Authuserfile/home/fellowship/.htpasswdrequire Valid-user
Password-protected files
AuthName "One still does not simply" AuthType basicauthuserfile/home/fellowship/.htpasswd<files "ONE-RING.O" > Require valid-user</files><filesmatch ^ ((one|two|three)-rings?\.o) $>require Valid-user</filesmatch >
Filtering visitors via referrer
This denies access for all users who is coming from (referred by) a specific domain.
Source
Rewriteengine on# Options +followsymlinksrewritecond%{http_referer} somedomain\.com [Nc,or]rewritecond%{HTTP_ REFERER} anotherdomain\.comrewriterule. *-[F]
Prevent other Web pages from being nested
This prevents the website-to is framed (i.e. put into iframe
a tag) and when still allows framing for a specific URI.
Setenvif Request_uri "/starry-night" Allow_framing=trueheader set x-frame-options sameorigin env=!allow_framing
Performance Compressed Files
<ifmodule mod_deflate.c> # Force compression for mangled headers. # http://developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping <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 A Pache 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 ' are 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-compo nent Text/xml </IfModule></IfModule>
Source
Set Expiration header information
Expires headers tell the browser whether they should request a specific file from the server or just grab it from The cache. It is advisable to set static content ' s expires headers to something far in the future.
If you don't control versioning with filename-based cache busting, consider lowering the cache time for resources like CSS And JS to something like 1 week. Source
<ifmodule mod_expires.c> expiresactive on ExpiresDefault "Access plus 1 m Onth "# CSS expiresbytype text/css" Access plus 1 Year "# Data interchange Expiresbyt ype Application/json "Access plus 0 seconds" Expiresbytype application/xml " Access plus 0 seconds "expiresbytype text/xml" Access plus 0 Seconds "# Favicon (Cannot b E renamed!) Expiresbytype Image/x-icon "Access plus 1 week" # HTML components (HTCs) Expiresbytype text/x -component "Access plus 1 month" # HTML expiresbytype text/html "Acce SS Plus 0 Seconds "# JavaScript expiresbytype application/javascript" Access plus 1 year "# Manifest F Iles 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" E Xpiresbytype 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 AP Plication/font-woff "Access plus 1 month" Expiresbytype application/vnd.ms-fontobject "Access p LUs 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 off the ETAGS flag
ETag
by removing the header, you disable caches and browsers from being able to validate files, so they is forced to rel Y on your Cache-Control
and Expires
header. Source
<ifmodule mod_headers.c> Header unset etag</ifmodule>fileetag None
Miscellaneous Setting PHP variables
Php_value <key> <val># for Example:php_value upload_max_filesize 50mphp_value max_execution_time 240
Custom Error Pages
ErrorDocument "Houston, we have a problem." ErrorDocument 401 Http://error.example.com/mordor.htmlErrorDocument 404/errors/halflife3.html
Force download
Sometimes want to force the browser to download some content instead of displaying it.
<files *.md> forcetype application/octet-stream Header set content-disposition attachment</files >
Now there are a yang to this yin:
Block download
Sometimes you want to force the browser to display some content instead of downloading it.
<filesmatch "\. (tex|log|aux) $ "> Header set Content-type text/plain</filesmatch>
Run cross-domain font references
Cdn-served Webfonts might not work in Firefox or IE due to CORS. This snippet solves the problem.
<ifmodule mod_headers.c> <filesmatch "\. ( EOT|OTF|TTC|TTF|WOFF|WOFF2) $ "> Header Set access-control-allow-origin" * " </filesmatch></ Ifmodule>
Source
Auto UTF-8 Encode
Your text content should always be UTF-8 encoded, no?
# Use UTF-8 encoding for anything served Text/plain or text/htmladddefaultcharset utf-8# Force UTF-8 for a number of the file for Matsaddcharset utf-8. Atom. css. js. json. rss. VTT. xml
Source
Switch PHP version
If you ' re on a shared host, chances is there is more than one version of PHP installed, and sometimes you want a specifi C version for your website. For example, Laravel requires PHP >= 5.4. The following snippet should switch the PHP version for you.
AddHandler application/x-httpd-php55 php# Alternatively, you can use Addtypeaddtype application/x-httpd-php55. php
Disable IE Compatibility view
Compatibility View in IE, affect how some websites is displayed. The following snippet should force IE to use the Edge Rendering Engine and disable the compatibility View.
<ifmodule mod_headers.c> browsermatch MSIE is-msie Header set x-ua-compatible Ie=edge env=is-msie</ Ifmodule>
Support WEBP Picture format
If WebP images is supported and an image with a. WebP extension and the same name was found at the same place as the jpg/p Ng image that is going to being served, then the WebP image is served instead.
Rewriteengine Onrewritecond%{http_accept} image/webprewritecond%{document_root}/$1.webp-frewriterule (. +) \. (jpe?g|png) $ $1.WEBP [t=image/webp,e=accept:1]
. htaccess Use Daquan