Home >Backend Development >PHP Tutorial >[Transfer] Bind domain name to subdirectory_PHP tutorial
When we install a forum or blog on a virtual host, in order to facilitate management, we will install it in a folder under the root directory (www/web directory). For example, if I install a Discuz forum, I A new bbs directory will be created in the root directory, and then the Discuz installation program will be uploaded to this directory for installation. After the installation is completed, the address where we access the forum will become: http://www.example.com/bbs ( http://www.example.com/bbs/forum.php), but this will be a bit uncomfortable. After all, our domain name is: http://www.example.com. We only want to use this domain name to directly Visit our forum without adding a bbs subdirectory. At this time, the URL forwarding record comes into play. It was born to solve this type of problem, so that it can also be used to implement pseudo-static URLs. This is not the purpose of this article. Topic, here we only discuss how to use URL forwarding technology to forward domain names to subdirectories. As for what URL forwarding is, I won’t go into it here. It is everywhere on Baidu. Let’s just talk about how to implement it.
(1) We create a new .htaccess text file locally. Note that .htaccess is the name of this text file, so the full name of the text file is: .htaccess.txt
(2) Write the following code in the text file:
<span> 1</span> <span># 将 RewriteEngine 模式打开 </span><span> 2</span> <span>RewriteEngine On </span><span> 3</span> <span> 4</span> RewiteBase / <span> 5</span> <span> 6</span> RewriteCond %{HTTP_HOST} ^(www\.)?<span>example\.com$ [NC] </span><span> 7</span> RewriteCond %{REQUEST_URI} !^/bbs/ <span> 8</span> RewriteCond %{REQUEST_FILENAME} !-<span>f </span><span> 9</span> RewriteCond %{REQUEST_FILENAME} !-<span>d </span><span>10</span> RewriteRule ^(.*)$ bbs/$<span>1</span> <span>11</span> <span># 没有输入文件名的默认到到首页 </span><span>12</span> RewriteCond %{HTTP_HOST} ^(www\.)?<span>example\.com$ [NC] </span><span>13</span> RewriteRule ^(/)?$ bbs/forum.php [L]
(3) Remove the extension .txt from the text file, and use the ftp upload tool to upload it to the root directory of the website (www/web directory). Note that this must be the root directory of the website. We also need to write this file when doing URL staticization in SEO optimization settings, but the .htaccess file must be placed in the bbs directory.
Now you can access the forum as long as you visit: http://www.example.com
Note: (.htaccess file explanation)
[RewriteEngine On] means that the rewrite engine is on or off. The function is to conveniently turn on or off the following statements, so that there is no need to comment statements one by one.
[RewriteCond %{HTTP_HOST} ^(www.)?example.com$ [NC]] represents the rewrite condition. The preceding %{HTTP_HOST} represents the currently visited URL, which only refers to the prefix part. The format is www.example.com excluding "http://" and "/", ^ means the beginning of the string, $ means the end of the string, . means escaped., it is fine if not escaped, escaping is recommended. In case some servers do not support it, ? means that the preceding bracket www. appears 0 or 1 times. The meaning of this rule is that if the URL visited is example.com or www.example.com, execute the following statement. If it does not match, skip it. . Also, there is no guarantee that the URL entered by everyone is in lowercase. If the URL is entered in uppercase, the Linux system is case-sensitive, so [NC] should be added after RewriteCond to ignore case.
[RewriteCond %{REQUEST_URI} !^/bbs/] is also a rewriting condition. %{REQUEST_URI} represents the relative address of access, which is the address relative to the root directory, which is the component behind the domain name/. The format includes the first "/", ! means non, this statement means that the accessed address does not start with /bbs/, but only starts with ^ and does not end with $
[RewriteCond %{REQUEST_FILENAME} !-f]
[RewriteCond %{REQUEST_FILENAME} !-d]
The meaning of these two statements is that the requested file or path does not exist. If the file or path Exists will return an already existing file or path
[RewriteRule ^(.*)$ bbs/$1] represents the rewrite rule. The most important part means that when the above RewriteCond conditions are met, this rewrite will be executed. Rule, ^(.*)$ is a regular expression match, matching the current requested URL, ^(.*)$ means matching any character of the current URL, . means any single character, * means matching 0 times or N times (N>0), the following /bbs/$1 is a rewriting component, which means that the previously matched character is rewritten as /bbs/$1. This $1 represents a reverse match and refers to the component of the first parenthesis. That is, .* in ^(.*)$.
—————————————————————————————————— ————————————————————————————————————————————
Attached below are simple grammar rules and flags:
[RewriteCond syntax:]
RewriteCond TestString CondPattern [flags]
Other uses of rewritecond:
'-d' (directory)
Treat TestString as a path name and test whether it is an existing directory.
‘-f’ (regular file)
Treat TestString as a pathname and test whether it is an existing regular file.
‘-s’ (non-empty regular file)
Treat TestString as a pathname and test whether it is an existing regular file with size greater than 0.
‘-l’ (symbolic link)
Treat TestString as a pathname and test whether it is an existing symbolic link.
‘-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’ (for files that exist in subrequests)
Checks whether TestString is a valid file and can be accessed under the server’s current access control configuration. It uses an internal subrequest to do the check. It will reduce the performance of the server, so please use it with caution!
‘-U’ (URL that exists for the subrequest)
Checks whether TestString is a valid URL and can be accessed under the current access control configuration of the server. It uses an internal subrequest to do the check. It will reduce the performance of the server, so please use it with caution!
[RewriteRule syntax:]
RewriteRule Pattern Substitution [flags]
【flags】:
‘chain|C’ (link next rule)
This tag links the current rule to the next rule. It has the effect that if a rule is matched, its subsequent rules will continue to be processed, that is, this mark will have no effect; if the rule is not matched, its subsequent rules will be skipped. For example, when performing an external redirect in a directory-level rule, you may need to remove ".www" (".www" should not appear here).
‘cookie|CO=NAME:VAL:domain[:lifetime[:path]]’ (set cookie)
Set a cookie on the client side. The name of the cookie is NAME and the value is VAL. Domain is the domain of the cookie, such as '.apache.org', optional lifetime is the validity period of the cookie (minutes), and optional path is the path of the cookie.
'env|E=VAR:VAL' (set environment variable)
This tag sets the value of the environment variable VAR to VAL. VAL can contain the expandable 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 situations, usually in XSSI () or CGI ($ENV{'VAR'}), but also in subsequent The CondPattern parameter of the RewriteCond directive is referenced via %{ENV:VAR}. Use this to remember information stripped from the URL.
‘forbidden|F’ (forbidden URL)
Forcibly ban the current URL, that is, immediately feedback an HTTP response code 403 (forbidden). Using this tag, you can chain several RewriteConds to conditionally block certain URLs.
‘gone|G’ (forced abandoned URL)
Force the current URL to be abandoned, that is, immediately feedback an HTTP response code 410 (obsolete). Use this tag to indicate that the page has been abandoned and no longer exists.
‘handler|H=Content-handler’ (mandatory content handler specification)
Force the custom content handler of the target file to be Content-handler. For example, the ScriptAlias directive is used to emulate the mod_alias module to force all files within the mapped folder to be processed by the "cgi-script" processor.
‘last|L’ (end rule)
Stops the rewrite operation immediately and no other rewrite rules are applied. It corresponds to the last command in Perl or the break command in C language. This tag is used to prevent the currently rewritten URL from being rewritten again by subsequent rules. For example, you can use it to rewrite the URL of the root path (‘/’) to an actual URL (for example: ‘/e/www/’).
‘next|N’ (start over)
Re-execute the rewrite operation (start over from the first rule). At this time, the URL processed again is no longer the original URL, but the URL processed by the last rewriting rule. It corresponds to the next command in Perl or the continue command in C language. This mark allows the rewrite operation to be restarted (immediately back to the beginning of the loop). But be careful not to create an infinite loop!
'nocase|NC' (ignore case)
It makes Pattern ignore case, that is, when Pattern matches the current URL, 'A-Z' and 'a-z' There is no difference.
'noescape|NE' (do not escape URIs in output)
This tag prevents mod_rewrite from applying normal URI escaping rules to the rewrite results. Under normal circumstances, special characters ('%', '$', ';', etc.) will be escaped into equivalent hexadecimal encodings ('%25′, '%24', '%3B', etc.) . This flag prevents such escaping, allowing symbols such as percent signs to appear in the output, such as:
RewriteRule /foo/(.*) /bar?arg=P1%3d$1 [R,NE]
Can cause '/foo/zed' to be redirected to a safe request '/bar?arg=P1=zed'.
‘nosubreq|NS’ (Do not process internal subrequests)
This tag forces the rewrite engine to skip the rewrite rule when the current request is an internal subrequest. For example, when mod_include attempts to search the directory default file (index.xxx), Apache will generate a subrequest internally. Rewriting rules is not necessarily useful for subrequests, and it may even throw an error if the entire ruleset is in effect. Therefore, you can use this tag to exclude certain rules.
Usage guidelines: If you add a CGI script prefix to URLs to force them to be processed by CGI scripts, but the error rate (or resource overhead) of subrequest processing is high, in this case, you can use this tag .
'proxy|P' (force to proxy)
This flag causes the replacement component to be internally forced to be sent as a proxy request, and immediately interrupts the rewrite processing, then hands over the processing to the mod_proxy module . You must ensure that this replacement string is a valid URI that can be processed by mod_proxy (such as starting with http://hostname), otherwise you will get an error returned by the proxy module. Using this tag, certain 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 be enabled.
'passthrough|PT' (hand over to next processor)
This tag forces the rewrite engine to set the uri field in the internal request_rec structure to the value of the filename field, this little This flag is just a hack to enable post-processing of the output of RewriteRule directives, using Alias , ScriptAlias, Redirect, and other directives from various URI-to-filename translators.]. Give an example to illustrate its meaning: If you want to rewrite /abc to /def, and then use mod_alias to convert /def to /ghi, you can do this:
RewriteRule ^/abc(.*) /def$1 [ PT]
Alias /def /ghi
If the PT tag is omitted, although the part that rewrites uri=/abc/… to filename=/def/… works normally, subsequent mod_alias attempts to convert the URI An error will occur when reaching the file name.
Note: This tag must be used if you need to mix multiple modules that convert URIs to file names. . Mixing mod_alias and mod_rewrite here is a typical example.
‘qsappend|QSA’ (append query string)
This tag forces the rewrite engine to append a query string to the existing replacement string instead of simply replacing it. You can use this tag if you need to add information to the request string through rewriting rules.
'redirect|R [=code]' (forced redirect)
If Substitution starts with http://thishost[:thisport]/ (makes the new URL a URI), An external redirect can be forced. If no code is specified, an HTTP response code 302 (Temporary Move) is generated. If you need to use another response code in the range 300-400, just specify it here (or use one of the following symbolic names: temp (default), permanent, seeother). Use it to feed back the normalized URL to the client, such as rewriting "/~" to "/u/", or always adding a slash to /u/user, etc.
Note: When using this tag, you must ensure that the replacement field is a valid URL. Otherwise, it would point to an invalid location! And keep in mind that the tag itself just prefixes the URL with http://thishost[:thisport]/ and the rewriting operation will still proceed. Often, you will also want to stop the rewriting operation and redirect immediately, so you will also need to use the 'L' tag.
’skip|S=num’ (skip subsequent rules)
This tag forces the rewrite engine to skip num rules after the current matching rule. It can simulate an if-then-else structure: the last rule is a then clause, and the skip=N rules are else clauses. Note: It is different from the 'chain|C' tag!
‘type|T=MIME-type’ (forced MIME type)
Force the MIME type of the target file to MIME-type, which can be used to force the content type based on certain conditions. For example, the following command allows .php files to be displayed by mod_php according to the MIME type of the PHP source code (application/x-httpd-php-source) when called with the .phps extension:
RewriteRule ^(.+ .php)s$ $1 [T=application/x-httpd-php-source]