Apache. htaccess file

Source: Internet
Author: User
Tags apache error log deprecated parent directory php source code response code file permissions password protection

Today the thinkphp URL pattern is http://localhost/mythinkphp/index.php/index/user/id/1 by Normal mode (url_mode=1). HTML changed to rewrite mode

Http://localhost/mythinkphp/Index/user/id/1.html, thus implementing the hidden. index.php effect when accessing the Mythinkphp project all appeared with a server error error.

I first opened the LoadModule Rewrite_module modules/mod_ in the httpd.conf. rewrite.so rewrite mode, and then set the Htdocs folder's. htaccess file permissions, at which time access to the Mythinkphp project all appeared the server error error, I thought it was not open Htdocs folder AllowOverride property, and found that it is actually open in httpd.conf, the final troubleshooting problem is. htaccess file editing

<IfModule mod_rewrite.c>RewriteEngine On

The case of the problem, in fact, this problem in the Linux system configuration file has appeared many times, in the future must be highly detailed to the config file editing! There are also rewrite tools in the. htaccess file authoring rule, and regular expression rules for learning more.

<ifmodule mod_rewrite.c>
Rewriteengine on
Rewriterule ^ (. *) $ index.php/$1 [qsa,pt,l]

What is the. htaccess?

The. htaccess file (or "Distributed Profile") provides a way to configure a directory change by placing a file containing one or more directives in a particular document directory to act on this directory and all its subdirectories. As a user, the commands you can use are limited. The administrator can set it through Apache's allowoverride instructions.

As an overview, the htaccess file is a configuration file in the Apache server that is responsible for the Web page configuration under the relevant directory. Through the htaccess file, you can help us: page 301 redirect, custom 404 error page, change file extension, allow/block specific user or directory access, prohibit directory list, configure default document and other functions.

Enable. htaccess, you need to modify httpd.conf, enable allowoverride, and use allowoverride to limit the usage of specific commands. If you need to use a file name other than. htaccess, you can use the Accessfilename directive to change it. For example, if you need to use. config, you can configure it in the server configuration file as follows: Accessfilename. config.

Broadly speaking,. Htaccess can help us implement include: folder password protection, user Auto Redirect, custom error page, change your file extension, block specific IP address of the user, only allow the specific IP address of the user, prohibit directory list, and use other files as index files and other features.

Working principle

The. htaccess file (or "Distributed Profile") provides a way to change the configuration for each directory by placing a file containing instructions in a specific directory that acts on this directory and all its subdirectories.
If you need to use a file name other than. htaccess, you can use the Accessfilename directive to change it. For example, if you need to use. config, you can configure it in the server configuration file in the following ways:
Accessfilename. config
Typically, the. htaccess file uses the same configuration syntax as the master configuration file. The allowoverride directive determines, by category, which directives in the. htaccess file are valid. If an instruction is allowed to be used in. htaccess, in the instructions in this manual, this directive will have an overlay segment that describes the value that must be set in the AllowOverride directive in order for this directive to take effect.

(not) where the. htaccess file is used

      in general, you should not use. htaccess files unless you have no access to the master profile. There is a common misconception that user authentication can only be achieved through the. htaccess file, which is not true, and it is perfectly feasible to write user authentication in the main configuration file, and it is a good method. The
. htaccess file should be used when the content provider needs to change the configuration of the server for a specific directory without root privileges. If the server administrator is reluctant to modify the configuration frequently, you can allow the user to modify the configuration by using the. htaccess file itself, especially if the ISP runs multiple user sites on the same machine and wants the user to change the configuration themselves.
Even so, it is generally best to avoid using. htaccess files. Any configuration that you wish to place in the. htaccess file can be placed in the <Directory> section of the master profile and is more efficient. The
avoid using. htaccess files for two main reasons. The
is performance first. If the. htaccess file is enabled for allowoverride, Apache needs to find the. htaccess file in each directory, so whether or not it is actually used, enabling. Htaccess can result in degraded performance. In addition, for each request, you need to read the. htaccess file once.
Also, Apache must look for the. htaccess file in all superior directories to make all valid instructions work (see instructions for the entry into force), so if you request a page in/www/htdocs/example, Apache must look for the following files:
has a total of 4 additional files to access, even if none of these files exist. (Note that this may only be due to allowing the root directory "/" to be used. htaccess, although this is not a lot.) )

Next is security. This allows the user to modify the configuration of the server itself, which may lead to some unexpected modifications, so consider carefully whether the user should be given such privileges. However, if the user is given less privileges to meet their needs, additional technical support requests will be made, so you must explicitly tell the user what permissions have been given to them, explain the values set by allowoverride, and guide them through the instructions to avoid a lot of trouble in the future.
Note that placing instructions in the. htaccess file in the/www/htdocs/example directory is exactly equivalent to placing the same instruction in the <Directory/www/htdocs/example> segment in the main configuration file.

Contents of the. htaccess file in the/www/htdocs/example directory:
AddType text/example. EXM
Excerpt from the httpd.conf file:
AddType text/example. EXM
However, it is more efficient to put the configuration in the master configuration file because it needs to be read only once at Apache startup, not every time the file is requested.
Setting allowoverride to none can completely prohibit the use of. htaccess files:
AllowOverride None

Scope of Instruction

The configuration directives in the. htaccess file act on the directory where the. htaccess file resides and all of its subdirectories, but it is important to note that The parent directory may also have. htaccess files, and directives are in order of lookup, so directives in a. htaccess file in a specific directory may overwrite the directives in the. htaccess file in their parent directory, meaning that directives in subdirectories overwrite the parent directory or the instructions in the master configuration file.


If some of the directives in the. htaccess file do not work, there may be several reasons.
The most common reason is that the allowoverride directive is not set correctly, and you must ensure that no allowoverride is set for this file locale. A good test method is to add a bit of meaningless spam to the. htaccess file, and if the server does not return an error message, you can almost conclude that the allowoverride none is set.
When accessing a document, if you receive an error message from the server, you should check the Apache error log to know which directives are not allowed in the. htaccess file, and you may find syntax errors that need to be corrected.

. htaccess Tools

Will not write a friend, in this introduce a very good. htaccess redirection-url Rewrite tool rewriting-tool


htaccess Grammar Tutorials

Rewriteengine Onrewritecond%{http_host} ^ (www\.)? Xxx\.com$rewritecond%{request_uri}!^/blog/rewritecond%{request_filename}!-frewritecond%{REQUEST_FILENAME}!- Drewriterule ^ (. *) $/blog/$1# No input file name default to the home page Rewritecond%{http_host} ^ (www\.)? Xxx\.com$rewriterule ^ (/)? $ blog/index.php [L]

Here I begin to explain the above meaning:

"Rewriteengine on"
Indicates that the rewrite engine is on, off, and it is convenient to turn the following statements on or off so that no one comment statement is required.

"Rewritecond%{http_host} ^ (www\.)?" xxx\.com$ "
This is a rewrite condition, the previous%{http_host} represents the URL of the current visit, only refers to the prefix portion, the format is www.xxx.com does not include "http:/" and "/", ^ represents the beginning of the string, $ denotes the end of the string, \. Indicates escaped. , if not escaped, it is recommended to escape, to prevent some servers do not support,? Represents the front parenthesis www\. 0 or 1 occurrences, the rule means that if the URL visited is xxx.com or www.xxx.com executes the following statement, the non-conformance is skipped.

is also a rewrite condition,%{request_uri} means the relative address of the access, that is, the address of the relative root directory, is the domain name/back of the composition, the format includes the first "/", "!", which means the address of the access does not start with/blog/, just the beginning ^, no end $

These two sentences mean that the requested file or path does not exist, and if a file or path exists, it will return a file or path that already exists

"Rewriterule ^ (. *) $/blog/$1"
The overriding rule, the most important part, means that when the above rewritecond conditions are met, this rewrite rule will be executed, and ^ (. *) $ is a regular expression match that matches the current request of the url,^ (. *) $ meaning matches any character of the current URL. Represents any single character, * Indicates a match 0 or N times (n>0), the back/blog/$1 is an overriding ingredient, meaning that the preceding matching word rename characters is written as/blog/$1, which represents a reverse match, referring to the first parenthesis in front of the component, that is ^ (. *) $. *, there will be a problem here, discussed later.

"Rewritecond%{http_host} ^ (www\.)?" xxx\.com$ "
"Rewriterule ^ (/)? $ blog/index.php [L]"
This means that the requested host address is www.xxx.com, if the end of the address is only 0 or 1 "/", will be rewritten to the subdirectory of the home page, I guess this is mainly because the rewritten address is not automatically find the home page, you need to specify.

Now to talk about the problem that arises, Rewriterule ^ (. *) $/blog/$1 The former part ^ (. *) $ will match the URL of the current request.
For example: The request URL is http://www.xxx.com/a.html, whether to match the entire http://www.xxx.com/a.html, or just match/a.html that is behind the backslash, or just match a.html.
The answer is: according to rewritebase rules, if the rewritebase is/, will match a.html, without the preceding backslash, so the last statement should be written rewriterule ^ (. *) $ blog/$1 (without/), However, the actual application with the front of the backslash, can also be used, may not take the line. Now the problem comes out, if not set Rewritebase to/, will match the entire URL http://www.xxx.com/a.html, obviously this is wrong, so should add this: rewitebase/

Another problem is that there is no guarantee that the URLs entered by everyone are lowercase, and if the input is uppercase, the Linux system is case-sensitive, so you should add [NC] to ignore the case after Rewritecond.

At this point, the complete statement should be:

Rewriteengine Onrewitebase/rewritecond%{http_host} ^ (www\.)? xxx\.com$ [Nc]rewritecond%{request_uri}!^/blog/rewritecond%{request_filename}!-frewritecond%{REQUEST_FILENAME}! -drewriterule ^ (. *) $ blog/$1# No input file name default to the home page Rewritecond%{http_host} ^ (www\.)? xxx\.com$ [Nc]rewriterule ^ (/)? $ blog/index.php [L]

If you continue to have statements later, you should not add the last [L], because this is the meaning of the last statement.

Anti-theft chain statements, also need to add rewitebase/, as follows:

Rewriteengine Onrewitebase/rewritecond%{http_referer}!^$ [Nc]rewritecond%{http_referer}!xxx.info [NC]RewriteRule \ . (jpg|gif|png|bmp|swf|jpeg) $/error/daolian.gif [r,nc,l]

If you continue to have a statement later, you should not add the last [l],/error/daolian.gif image that appears when someone hotlinking.

The following is a simple grammar rule and flags

"Rewritecond Syntax"
Rewritecond teststring Condpattern [flags]

Other uses of Rewritecond:
"-D" (directory)
Treat TestString as a pathname and test whether it is a directory that exists.
"-F" (regular file)
Treat teststring as a path name and test whether it is a regular file that exists.
"-S" (non-empty regular file)
Treat TestString as a pathname and test whether it is an existing regular file with a size greater than 0.
"-L" (symbolic Connection)
Treat TestString as a pathname and test whether it is an existing symbolic connection.
"-X" (executable)
Treat TestString as a pathname and test whether it is an existing file with executable permissions. This permission is detected by the operating system.
"-F" (Files that exist on a child request)
Check if teststring is a valid file and can be accessed under the current access control configuration of the server. It uses an internal sub-request to do the check, because it will reduce the performance of the server, so please use it carefully!
"-U" (the URL where the child request exists)
Check if teststring is a valid URL and can be accessed under the current access control configuration of the server. It uses an internal sub-request to do the check, because it will reduce the performance of the server, so please use it carefully!

"Rewriterule Syntax:"
Rewriterule Pattern Substitution [flags]

"Chain| C "(link next rule)
This tag links the current rule to the next rule. It produces this effect: if a rule is matched, it continues to process its successor, that is, the tag does not work, and if the rule is not matched, its successor rule is skipped. For example, when performing an external redirect in a directory-level rule, you may need to delete ". www" (". www" should not appear here).

"cookie|co=name:val:domain[:lifetime[:p Ath]]" (Set Cookies)
Set a cookie on the client. The name of the cookie is "name" and the value is Val. Domains are the domain of the cookie, such as ". Apache.org", the optional lifetime is the lifetime of the cookie (in minutes), and the optional path is the cookie.

"Env| E=var:val "(Setting environment variables)
This tag will have an environment variable var value of Val,val that can contain extensible regular expression inverse references ($N and%n). This tag can be used multiple times to set multiple variables. These variables can be indirectly referenced in many subsequent cases, usually in Xssi (<!– #echo var= "var" –>) or CGI ($ENV {"var"}). It can also be referenced by%{env:var} in the Condpattern parameter of the subsequent rewritecond instruction. Use it to remember the information that is stripped from the URL.

"Forbidden| F "(Enforce forbidden URL)
Forces the current URL to be suppressed, that is, to immediately respond to an HTTP response code of 403 (forbidden). With this tag, you can link several rewriteconds to conditionally block certain URLs.

"Gone| G "(Mandatory deprecated URL)
Forces the current URL to be deprecated, that is, immediately feedback an HTTP response code of 410 (deprecated). Using this tag, you can indicate that the page has been deprecated and does not exist.

"Handler| H=content-handler "(enforces the specified content processor)
Changzi the content processor for the target file is Content-handler. For example, the Scriptalias directive used to emulate the Mod_alias module to force all files in the mapped folder to be handled by the "Cgi-script" processor.

"Last| L "(End rule)
Stops the rewrite operation immediately and no longer applies another rewrite rule. It corresponds to the last command in Perl or the break command in the C language. This flag is used to prevent URLs that are currently overridden from being rewritten again by subsequent rules. For example, you can use it to override the URL of the root path ("/") to a URL that actually exists (for example: "/e/www/").

"Next| N "(from scratch)
Re-executes the rewrite operation (starting with the first rule). The URL that was processed again at this point is not the original URL, but the URL that was processed by the last rewrite rule. It corresponds to the next command in Perl or the Continue command in the C language. This tag can restart the rewrite operation (immediately to the beginning of the loop). But be careful not to create a dead loop!

"Nocase| NC "(ignoring case)
It makes the pattern ignore case, that is, "A-Z" and "A-Z" do not differ when pattern matches the current URL.

"Noescape|ne" (the URI is not escaped in the output)
This flag prevents Mod_rewrite from applying a general URI escape rule to the overridden result. In general, special characters ("%", "$", ";") And so on) are escaped to the equivalent hexadecimal encoding ("%25′,"%24′, "%3b", etc.). This flag prevents such escapes from allowing symbols such as percent signs to appear in the output, such as:
rewriterule/foo/(. *)/bar?arg=p1\%3d$1 [R,ne]
You can turn the/foo/zed to a secure request "/bar?arg=p1=zed".

"Nosubreq| NS "(Do not process internal sub-requests)
This token forces the rewrite engine to skip the rewrite rule when the current request is an internal child request. For example, when Mod_include tries to search the directory default file (INDEX.XXX), Apache generates a child request internally. For a child request, the rewrite rule is not necessarily useful, and it may even throw an error if the entire rule set works. Therefore, you can use this tag to exclude certain rules.
Usage guidelines: If you add a CGI script prefix to a URL to force them to be handled by a CGI script, the error rate (or resource overhead) of the child request processing is high, in which case the token can be used.

"Proxy| P "(Mandatory for proxy)
This token causes the replacement component to be internally forced to send as a proxy request, and immediately interrupts the rewrite process and then transfers the processing to the Mod_proxy module. You must make sure that this replacement string is a valid URI that can be processed by mod_proxy (for example, starting with http://hostname), or you will get an error returned by a proxy module. With this tag, some remote components can be mapped to the local server domain name space, thereby enhancing the functionality of the Proxypass directive.
Note: To use this feature, the Mod_proxy module must already be enabled.

"Passthrough|pt" (hand over to the next processor)
This flag forces the rewrite engine to set the URI field in the internal REQUEST_REC structure to the value of the FileName field, a small modification that allows the output of the rewriterule instruction to be Alias, Scriptalias, from the URI to the file name, Redirect and other instructions for follow-up processing [original: This flag was just a hack to enable post-processing of the output of rewriterule directives, using Ali As, Scriptalias, Redirect, and other directives from various uri-to-filename translators. Give an example of what it means: if you want to rewrite/abc to/def, and then use Mod_alias to convert/def to/ghi, you can:
Rewriterule ^/abc (. *)/def$1 [PT]
If the PT mark is omitted, though the uri=/abc/... Rewrite for filename=/def/... Section works fine, but subsequent mod_alias are invalidated when attempting to convert a URI to a file name.
Note: You must use this tag if you need to mix multiple modules that convert URIs to file names: Mixed use of Mod_alias and mod_rewrite here is a typical example.

"Qsappend| QSA "(append query string)
This flag forces the rewrite engine to append a query string to an existing replacement string, rather than a simple replacement. You can use this tag if you need to add information to the request string through a rewrite rule.

"Redirect| R [=code] "(forced redirection)
If substitution begins with http://thishost[:thisport]/(making the new URL a URI), an external redirect can be enforced. If code is not specified, an HTTP response code of 302 (temporary move) is generated. If you need to use a different response code in the range of 300-400, just specify it here (or use one of the following symbol names: Temp (default), Permanent, seeother). You can use it to feed the normalized URL back to the client, such as "/~" to "/u/", or always to/u/user with a slash, and so on.
Note: When you use this tag, you must make sure that the replacement field is a valid URL. Otherwise, it will point to an invalid location! And keep in mind that this tag itself simply adds a http://thishost[:thisport]/prefix to the URL, and the rewrite operation continues. In general, you will also want to stop the rewrite operation and immediately redirect, then you need to use the "L" tag.

"Skip| S=num "(Skip the successor rule)
This flag forces the rewrite engine to skip NUM rules after the current matching rule. It simulates the IF-THEN-ELSE structure: The last rule is the then clause, and the skip=n rule that is skipped is the ELSE clause. Note: it and "chain| C "tag is different!

"Type| T=mime-type "(Force MIME type)
The force target file has a MIME type of mime-type and can be used to force the content type to be set based on certain conditions. For example, the following instruction allows a. php file to be displayed by mod_php according to the MIME type of the PHP source code (APPLICATION/X-HTTPD-PHP-SOURCE) in the case of a. Phps extension:
Rewriterule ^ (. +\.php) S $ $ [T=application/x-httpd-php-source]

. htaccess instances

Http://cloudbbs.org/forum.php?mod=viewthread&tid=7455&page=1&extra= #pid41053

Reference: http://baike.baidu.com/view/91163.htm

Apache. htaccess file

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.