The common usage of htaccess.

Source: Internet
Author: User
Tags json require valid webp http strict transport security


Re-redirect

Note: First you need the server to install and enable the Mod_rewrite module.
Mandatory www

Rewriteengine on
Rewritecond%{http_host} ^example\.com [NC]
Rewriterule ^ (. *) $ http://www.example.com/$1 [L,R=301,NC]

  Mandatory www common 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.


forced Non-www

is the www good, or non-www good, there is no conclusion, if you like without the WWW, you can use the following script:

Rewriteengine on
Rewritecond%{http_host} ^www\.example\.com [NC]
Rewriterule ^ (. *) $ http://example.com/$1 [l,r=301]

   Mandatory Non-www General method

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.
# 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 through proxy

If you use a proxy, this method is useful to you.

Rewritecond%{http:x-forwarded-proto}!https
Rewriterule (. *) Https://%{http_host}%{request_uri}

   force add trailing slash

Rewritecond%{request_uri}/+[^\.] +$
Rewriterule ^ (. +[^/]) $%{request_uri}/[r=301,l]

   take off the trailing slash

Rewritecond%{request_filename}!-d
Rewriterule ^ (. *)/$/$1 [r=301,l]

   redirect to a page

Redirect 301/oldpage.html http://www.example.com/newpage.html
Redirect 301/oldpage2.html http://www.example.com/folder/

   Directory alias

Rewriteengine on
Rewriterule ^source-directory/(. *) target-directory/$1

   Script alias

fallbackresource/index.fcgi

This is example has a index.fcgi file in some directory, and any requests within ' directory that fail to resolve a filen Ame/directory would be sent to the index.fcgi script. It ' s Good if you are want Baz.foo/some/cool/path to is handled by BAZ.FOO/INDEX.FCGI (which also supports requests to Baz.foo) While maintaining baz.foo/css/style.css and the. Get access to the original path from the PATH_INFO environment variable, as exposed to your scripting.

Rewriteengine on
Rewriterule ^$ index.fcgi/[qsa,l]
Rewritecond%{request_filename}!-f
Rewritecond%{request_filename}!-d
Rewriterule ^ (. *) $ index.fcgi/$1 [qsa,l]

This is a less efficient version of the Fallbackresource directive (because using mod_rewrite are more complex than ha Ndling the fallbackresource directive), but it ' s also more flexible.


  REDIRECT Entire Web site

Redirect 301/http://newsite.com/

This is way does it with links intact. This is www.oldsite.com/some/crazy/link.html'll become www.newsite.com/some/crazy/link.html. This is extremely helpful the are just "moving" a site to a new domain. Source


Clean URLs

This snippet lets your use "cleaning" urls-those without a PHP extension, e.g. Exa Mple.com/users instead of 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

But wait, this'll lock your out from your content as well! Thus Introducing ...


  Deny all access (exclude part)

# # 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 is your IP. If you replace the last three digits with 0/12 For example, this'll specify a range of IPs within the same network, thus Saving you are the trouble to list all allowed IPs separately. Source

Now of course there ' a reversed version:


   Shielding Crawler/malicious access

# # Apache 2.2
Order Deny,allow
Allow from all
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

   protect hidden files and directories

Hidden files and directories (those whose names start with a dot.) should most, if not all, of the time is secured. For example:. htaccess,. htpasswd,. Git, ... hg ...

Rewritecond%{script_filename}-d [OR]
Rewritecond%{script_filename}-F
Rewriterule "(^|/) \."-[F]

Alternatively, you can just raise a is not Found error giving the attacker dude no clue:

Redirectmatch 404/\. *$

   Securing backup files and source code files

These files are left by some text/html editors (like Vi/vim) and pose a great the 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>

   Prohibit directory browsing

Options all-indexes

   Prohibit picture hotlinking

Rewriteengine on
# Remove The following line if your want to block blank referrer too
Rewritecond%{http_referer}!^$

Rewritecond%{http_referer}!^http (s)?:/ /(.+\.)? example.com [NC]
Rewriterule \. (jpg|jpeg|png|gif|bmp) $-[nc,f,l]

# If you are want to display a ' blocked ' banner in place of the hotlinked image,
# Replace the above rule with:
# rewriterule \. (jpg|jpeg|png|gif|bmp) http://example.com/blocked.png [r,l]

   Prohibit picture hotlinking (specify domain name)

Sometimes you want to prohibit pictures hotlinking from some bad guys only.

Rewriteengine on
Rewritecond%{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 are want to display a ' blocked ' banner in place of the hotlinked image,
# Replace the above rule with:
# rewriterule \. (jpg|jpeg|png|gif|bmp) http://example.com/blocked.png [r,l]

   Password protected directory

The need to create a. htpasswd file somewhere in the system:

Htpasswd-c/home/fellowship/.htpasswd Boromir

Then can use it for authentication:

AuthType Basic
AuthName "One does not simply"
authuserfile/home/fellowship/.htpasswd
Require Valid-user

   password-protected 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>

   filter visitors via referrer

This denies access to all users who are coming from (referred by) a specific domain.
Source

Rewriteengine on
# Options +followsymlinks
Rewritecond%{http_referer} somedomain\.com [Nc,or]
Rewritecond%{http_referer} anotherdomain\.com
Rewriterule. *-[F]

   prevent being nested by another Web page

This prevents the "website to be framed" (i.e. put in an IFRAME tag) while still allows the for a framing URI.

Setenvif Request_uri "/starry-night" allow_framing=true
Header Set X-frame-options sameorigin env=!allow_framing

  Performance


   Compress 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 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 Expiration header information

Expires headers tell the browser whether they should request a specific file to the server or just grab it from the Cach E. 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 And JS to something like 1 week. Source

<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 off the ETAGS flag

By removing the ETag header, your disable caches and browsers from being able to validate files, so they are to forced On your cache-control and Expires headers. Source

<ifmodule mod_headers.c>
Header unset ETag
</IfModule>
Fileetag None

  other


  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 "Houston, we have a problem."
ErrorDocument 401 http://error.example.com/mordor.html
ErrorDocument 404/errors/halflife3.html

  Force download

Sometimes you want to enforce 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:


  Prevent downloads

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>

  Running 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>


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/html
Adddefaultcharset Utf-8

# Force UTF-8 for a number of file formats
Addcharset utf-8. Atom. css. js. json. rss. VTT. xml


   Toggle PHP Version

If you are in a shared host, chances are there are 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, can use AddType
AddType application/x-httpd-php55. php

   Prohibit IE compatible view

Compatibility View in IE could affect how some websites are displayed. The following snippet should enforces IE to use the Edge Rendering Engine and disable 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 are supported and an image with a. WebP extension and the same name are found at the same place as the jpg/p Ng image is going to being served, then the WebP image is served instead.

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]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.