[PHP] htaccess Quest

Source: Internet
Author: User
Tags 403 forbidden error password protection

. htaccess access Control (Allow/deny) 1. Verify that support is supported .htaccess

Create a new file in the directory .htaccess , essay input A string of characters (meaningless), see what reaction, if it is a 500 error, indicating that the current environment is supported .htaccess

fjdklsaj

Reprint Please specify: HTTP://WWW.CNBLOGS.COM/GANIKS/2. Deny from all

# no one gets in here!deny from all

3. Order command

The Order command is a pain point and the basis for configuring Apache, which determines the order in which Apache handles access rules.

With the Allow,deny parameter, Apache first finds and applies the Allow command, and then applies the Deny command to block all access.
With the Deny,allow parameter, Apache first finds and applies the Deny command, and then applies the Allow command to permit all access.

Assume that the local IP is192.168.4.126

Order Deny,AllowDeny from AllAllow from 192.168.4.126

Local access succeeded, non-local IP access 403 Forbidden4. Using the. htaccess filter domain name or network host (Allow/deny)

The following example restricts all network hosts that have "domain.com" access to the Web site:

Order Allow,DenyAllow from allDeny from .*domain\.com.*
5. Prohibit access to specified files
Order Deny,AllowDeny from AllAllow from 192.168.4.126 <Files favicon.ico>order allow,denydeny from all</Files>

6. Prohibit access to files of the specified type

Order Deny,AllowDeny from AllAllow from 192.168.4.126 <FilesMatch ".(txt|ico)$">order allow,denydeny from all</FilesMatch>

The wavy lines after files are used to turn on the regular expression analysis. Please note that this is an obsolete usage and Apache is more recommended to use the directive [3]
The regular expression must be between the double quotation marks, and refer to the ". htaccess Regular Expressions" Article of this site for the use of regular expressions for htaccess.
Pipe character in double quotation marks (|) Used to separate two file types (. log and. exe), which is equivalent to the logical "or"
The order command must be embedded in the Files section, or it will be applied to all files
Satisfy all means that both the host level (Allow/denay) and the user level (Require) must be met at the same time, and all is the default value, and the row can be omitted.

Password protection and verification using. htaccess

Do not study directory browsing with home page 1. Enable and disable directory browsing

Options All -IndexesIndexIgnore *Options All +Indexes

These 3 settings correspond to the following 3 graphs:



2. Disable browsing of certain files

IndexIgnore *.php *.txt~ Copy*

3. Customize the style of the Directory browsing page

<IfModule mod_autoindex.c> IndexOptions FancyIndexing </ifModule>

http://corz.org/public/images/demo/
Http://corz.org/server/resources/file_view.htaccess.txt?raw=true4. Configure Directory Home page files

DirectoryIndex index.html index.php index.htm
5. Configuration Error page
# custom error documentsErrorDocument 401 /err/401.phpErrorDocument 403 /err/403.phpErrorDocument 404 /err/404.phpErrorDocument 500 /err/500.php
URL rewriting and URL redirection
一、准备开始:mod_rewrite二、利用.htaccess实现URL重写(rewrite)与URL重定向(redirect)将.htm页面映射到.php临时重定向(R=302)与永久重定向(R=301)为什么要用重定向?——重定向和URL重写的区别长短地址转换去掉www加上www支持多域名访问三、改写查询字符串QUERY_STRING利用QSA转换查询字符串QUERY_STRING利用RewriteCond改写查询字符串QUERY_STRINGQSA与RewriteCond双剑齐发剥离查询字符串四、利用RewriteCond和RewriteRule进行访问控制文件访问控制用.htaccess阻止User-agent用.htaccess阻止盗链(hot-linking)References
1. Prepare to start: mod_rewrite
sudo a2enmod rewrite
<IfModule mod_rewrite.c>    Options +FollowSymlinks    RewriteEngine on    # More rules below    ...</IfModule>
    • FollowSymlinksMust be enabled, this is the security requirement of the rewrite engine
    • mod_rewriteAll URL requests submitted to Apache are processed and matched to the following rules
2. Use .htaccessImplementing URL rewriting and URL redirection 2.1 will .htmPage Map to .phpPage
<IfModule mod_rewrite.c>    Options +FollowSymlinks    RewriteEngine on    RewriteRule ^(.*)\.htm$ $1.php [NC]</IfModule>

[NC] No case (insensitive): The URL requested by the client is case insensitive
If you enter through the. htm, the browser address bar displays the. htm extension, but the actual execution on the server is. php
You must ensure that there is a corresponding. php on the server, otherwise it will be 404
Browsers and search engines can access Web pages simultaneously through. htm and. php

Test.htm
This is. htm
test.php
This is. php2.2 temporary redirect (r=302) with permanent redirect (r=301)

<IfModule mod_rewrite.c>    RewriteEngine on    RewriteBase /    RewriteRule ^(.*)\.htm$ $1.php [R,NC,L]</IfModule>

Precautions:

    • The Rewriterule is able to redirect. htm static pages to the. PHP Dynamic page
    • If you enter through the. htm, the browser address bar automatically transitions to. PHP, which is also the essence of redirection
    • You must ensure that there is a corresponding. php on the server, otherwise it will be 404
    • Browsers and search engines can access Web pages simultaneously through. htm and. php
    • If the. htm is present on the directory, it will be ignored
    • Rewritebase defines the overriding base directory.

      • For example, if you set up a virtual site under the/var/www directory, deleting this row will cause redirection to http://yourdomain.com/var/www/1.php. Obviously this is not found, and you do not want users to see the directory structure of your server.
    • As an example, if rewritebase/base/, then it will redirect to Http://yourdomain.com/base/1.php.
    • For overriding the base directory, we can also make a direct transformation by turning $1.php into/$1.php, so that rewritebase can be omitted.
    • The letter R indicates a temporary redirect equivalent to [R=302,NC]. For the redirect code, please refer to the HTTP protocol redirect encoding on this site.
    • The letter L indicates that if the rule can be matched, then this rule is the last one, ignoring the following rule.

<IfModule mod_rewrite.c>    RewriteEngine on    RewriteBase /    RewriteRule ^(.*)$ http://newdomain/$1 [R=301,NC,L]</IfModule>
    • This rule tells the browser and search engine, the website address has changed permanently, the user's URL request will be sent to the new domain name (host) processing.
    • Because it is redirected to the new host address, Rewritebase does not appear to be necessary.
2.3 Why redirect--the difference between redirection and URL rewriting
    • By redirecting, the browser knows the location of the page changes, thus changing the address displayed in the Address bar
    • By redirecting, the search engine realizes that the page has been moved, updating the search engine index, and removing the previously defunct link from the search results.
    • Temporary redirection (r=302) and permanent redirection (r=301) are pro-search engines and are an important technology for SEO
    • URL rewriting is used to map a page to another page of the site, and if overridden to another network host (domain name), it is processed by redirection
2.4 Short and long address translation

With URL rewriting, we can easily convert short and long addresses, but it is not appropriate to redirect them.

RewriteEngine OnRewriteRule ^grab /public/files/download/download.php

If you visit

http://mysite/grab?file=my.zip

The page is executed:

http://mysite/public/files/download/download.php?file=my.zip
2.5 Remove www
<IfModule mod_rewrite.c>    Options +FollowSymlinks    RewriteEngine on    RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]    RewriteRule ^(.*)$ http://%1/$1 [R=301,NC,L]</IFModule>
2.6 Plus www
<IfModule mod_rewrite.c>    Options +FollowSymlinks    RewriteEngine on    RewriteCond %{HTTP_HOST} ^(.*)$    RewriteRule (.*) http://www\.%1/$1 [R=301,L]</IFModule>
2.7 Support for multi-domain access

If you accidentally bought a host that doesn't support multiple domains, then. htaccess may be able to help you. Now suppose you have the domain name domain-one.com and domain-two.com, and the server root directory has the corresponding folder one and two, then the following rewrite will allow Apache to accept the two domain name request:

#two domains served from one root..RewriteCond %{HTTP_HOST} domain-one.comRewriteCond %{REQUEST_URI} !^/oneRewriteRule ^(.*)$ /one/$1 [L]RewriteCond %{HTTP_HOST} domain-two.comRewriteCond %{REQUEST_URI} !^/twoRewriteRule ^(.*)$ /two/$1 [L]
3. Rewrite the query string QUERY_STRING

The query string refers to the part of the URL request that follows the question mark. For example, the bold part of Http://mysite/grab?foo=bar is the query string, where the variable name is foo and the value is bar.

3.1 Using QSA to convert query strings query_string

QSA (query string appending) is used to intercept the query string in the URI, which is implemented by parentheses.

RewriteEngine OnRewriteRule /pages/(.+) /page.php?page=$1 [QSA]RewriteRule ^/([^/]+)/([^/]+)/? /index.php?first-var=$1&second-var=$2 [QSA]

Here, the simple links are mapped to the QSA through the /simple/flat/link/server-side.php?first-val=flat&second-var=link

    • Will map the request /pages/123?one=two to the/page.php?page=123&one=two
    • If there is no QSA flag, it will be mapped to the/page.php?page=123
    • If the parentheses are not used, the QSA is not required, as in "long and short address translation"
    • The parentheses regular expression can intercept the contents of the query string, but if the QSA flag is not turned on, then /page.php?page=$1 the part after the question mark will be stripped and discarded.
3.2 Rewrite the query string with Rewritecond query_string
RewriteEngine OnRewriteCond %{QUERY_STRING} foo=(.*)RewriteRule ^grab(.*) /page.php?bar=%1
    • This rule converts access request Http://mysite/grab?foo=bar to Http://mysite/page.php?bar=bar
    • Rewritecond is used to capture the value of the variable foo in the query string (query_string) and is stored in%1
    • Query_string is an Apache-defined "variable = value" Vector (array)
3.3 Qsa and Rewritecond double Jian Qi fa
RewriteEngine OnRewriteCond %{QUERY_STRING} foo=(.+)RewriteRule ^grab/(.*) /%1/index.php?file=$1 [QSA]
    • Will map the/grab/foobar.zip?level=5&foo=bar to/bar/index.php?file=foobar.zip&level=5&foo=bar.
    • The post-conversion root directory is the bar directory
    • The "question mark" in Foobar.zip?level=5 becomes the "ampersand" in the foobar.zip&level=5
3.4 Peel Query string

Simply add a "question mark" after the link you want to start stripping, and do not enable the QSA flag to peel the query string

RewriteEngine On# Whatever QS isRewriteCond %{QUERY_STRING} . # I don‘t want it with Question markRewriteRule foo.php(.*) /foo.php? [L]
4. Use RewriteCondAnd RewriteRuleFor access control

We have mentioned a lot of useful access control methods in the first Article Htaccess Foundation, in fact, through the rewrite can also achieve similar functions, and can be more powerful!

4.1 File access Control

Access controls previously implemented with order, files, and FilesMatch commands can meet most requirements, but when users are denied they see a huge "403 Forbidden", and if you don't want to hurt the user's feelings, you need to show something else, This feature can be achieved by rewrite:

RewriteEngine OnRewriteCond %{REQUEST_FILENAME} !^(.+)\.css$RewriteCond %{REQUEST_FILENAME} !^(.+)\.js$RewriteCond %{REQUEST_FILENAME} !special.zip$RewriteRule ^(.+)$ /chat/ [NC]

The rule will only allow users to request. CSS,. js types of files and Special.zip file
Rewriterule later specified restriction rules: Mapping to/char/directory processing
Rewritecond "exclamation point" (!) in the back of the Plays the "negation" function, it shows that the rewriterule rule is applied to those who do not meet the following regular expression, that is, no rules will be applied to files of the current type.
Rewritecond is a logical "and" connection, that is, only if the three conditions are not satisfied when the execution of Rewriterule
The rule also restricts access to. htm,. jpg, and other formats
The rule cannot be placed under the root directory (/) of the virtual site, or it will die in a loop
If it is a level two directory, such as/test/, then the parameters passed in Rewritecond start with/test/, so the file name obtained from (. +) also contains/test/, which the reader must be cautious about.
To get only the file name, you can replace (. +) with ([^/]+) and remove the symbol ^ as follows:

RewriteEngine OnRewriteCond %{REQUEST_FILENAME} !([^/]+)\.css$RewriteCond %{REQUEST_FILENAME} !([^/]+)\.js$RewriteRule ^(.+)$ /chat/ [NC]
4.2 use. htaccess to block User-agent

What is User-agent? User-agent is used to "tell" the browser to the server, or, more specifically, all HTTP clients have to use User-agent to "tell" the server so that the server responds differently to different clients. For example, a site may need to respond differently to browsers, search engine crawl, and various download tools. The server is differentiated by the so-called user-agent.
If your server provides downloads for certain resources, you will have to be cautious about downloading software such as "Thunder", as they may suck up your site resources and affect your normal visitor access. To do this, we can use rewrite to restrict access to certain UA:

RewriteEngine onRewriteCond %{HTTP_USER_AGENT} 2.0.50727 [NC]RewriteRule . abuse.txt [L]

This rule restricts the "Thunderbolt" client from downloading resources and resets the download file to Abuse.txt
Http_user_agent is an Apache built-in variable
2.0.50727 is the characteristic string of Thunderbolt user-agent
The "dot" behind rewriterule means "arbitrary uri", that is, whatever is requested, outputs Abuse.txt
Generally, we do not limit only one UA. Use [OR] to achieve unified processing of multiple UA:

RewriteEngine onRewriteCond %{HTTP_USER_AGENT} 2.0.50727 [NC,OR]RewriteCond %{HTTP_USER_AGENT} ^BlackWidow [NC,OR]# etc..RewriteCond %{HTTP_USER_AGENT} ^Net\ Vampire [NC]RewriteRule . abuse.txt [L]
4.3 use. htaccess block Hotlinking (hot-linking)

Hotlinking, especially the picture, is very shameful! Even if you copy the image to your own server, it is more than the theft of other people's image links to glory! (Spit Bad)
The rewrite function of the. Htaccess can provide a very simple and effective way to prevent this shameful behavior:

RewriteEngine OnRewriteCond %{HTTP_REFERER} !^$RewriteCond %{HTTP_REFERER} !^http://(www\.)?lesca\.me/ [NC]RewriteCond %{REQUEST_URI} !hotlink\.png [NC]RewriteRule .*\.(gif|jpg|png)$ /hotlink.png [NC]

Simply explain the functionality of the rule:

    • In addition to the site other than the website should not be referenced by the picture, the specific can be understood as
    • If the reference site is "empty" or "local", or if the referenced object is "Hotlink.png", then access is allowed
    • Again, the default logical connection Word between rewritecond is logical "with"
    • The difficulty here is to understand the logic transformation, namely the De Morgan law

Reprint Please specify: http://www.cnblogs.com/ganiks/htaccess regular expression

#位于行首时表示注释. F Forbidden (Forbidden): Command Server returns 403 Forbidden error to user browser [l]last rule (last rule): tells the server to stop rewriting url[n]next (next rule) after this rule has been executed: Tell the server to continue rewriting, Instructs all rewrite directives to execute [G]gone (missing): Command server returns 410 Gone (no longer exists) error message [P]proxy (proxy): tells the server to process user requests through the Mod_proxy module [C]chain (bundle): Tells the server to bundle the current rule with the previous rule [R]redirect (redirect): The command server issues a redirect message so that the user's browser issues a request for a rewritten/modified (rewrite/modify) URL [nc]no case]: The URL to the client request is case-insensitive [Pt]pass Through (release): Let the Mod_rewrite module return the rewritten URL to Apache for further processing [Or]or (logical OR): Connect two expressions with logic or "if the result is true" , the subsequent related rules are applied [Ne]no Escape (Disable Escape): The command server disables the escape character on output [Ns]no subrequest (disables the child request): Skips the current command if there is an internal child request [Qsa]append Query String (append query string): The command server appends the query string at the end of the URL [S=x]skip (skipped): If a specified condition is met, the following X-rule is skipped [e=variable:value]environmental Variable (environment variable): The command server assigns the value values to the variable variable[t=mime-type]mime type (MIME type): declares that the target resource belongs to a MIME type [] that matches a character set, for example [XYZ] can match X, Y or z[]+ for example [xyz]+ will match the occurrence of x, Y, z in any order, number of times [^] character ^ denotes a complement to the character set. [^XYZ] matches a string that does not have X, y, or Z [A-z] hyphen (-) to match all strings from letter A to letter Z A{n} Specifies that the number of occurrences of the letter A is n times, which matches when the condition is met. For example, x{3} matches only xxx a{n,} Specifies that the letter a appears at least n times, such as X{3, and that a match to XXX or xxxx a{n,m} Specifies that a appears at least N to M times. () is used toRegular expression groupings, strings that satisfy the first set of regular expressions are stored in the variable, and so on. If the parentheses are not regular expressions, for example (perishable)? Press will be able to match a press^ with or without a perishable prefix at the beginning of the line. Note: The meaning of [^] in brackets is different. $ at the end of the line? For example Monzas? Will match Monza or Monzas, and Mon (za)? Will match Mon or Monza. Another example of x? Matches "null character" or a x! logical non. For example, "!string" will match all strings except "string". Represents any string-command Apache "do not" rewrite the URL, such as "xxx.domain.com.*–[f" + matches at least one arbitrary character, for example g+ matches start with G, And a string that has at least one character at the back * matches 0 or more characters, for example ". *" matches any string | logical "or", unlike [or], which matches only strings, for example (X|y) matches x or y escape characters. You can escape the opening parenthesis (the sharp character ^ dollar sign $ exclamation point!). asterisk * Pipe symbol | closing parenthesis) etc. \. Escape is a dot character (a dot regular the expression can match any character)/* 0 or more forward slashes. * 0 or more arbitrary characters (that is, matches any string, including null characters) ^$ match "null character "," Blank line "^.*$ matches any string (one line only) [^/.] Matches any character that is not a forward slash or point [^/.] + matches the first character neither "forward slash" nor "point", the successor character can be a "forward slash" or "dot" of the string HTTP/n matches "http//" ^domain.* matches the string starting with "domain" ^domain\.com$ match only " Domain.com "-D test string is an existing directory-F test string is an existing file-s test string refers to whether the file has a" non-0 "value HTTP protocol redirection encoding 301–moved permanently302–moved Temporarily403–forbidden404–not Found410–gone

[PHP] htaccess Quest

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.