Home >Backend Development >PHP Tutorial >nginx location configuration

nginx location configuration

WBOY
WBOYOriginal
2016-08-08 09:27:161400browse
Grammar rules: location [=|~|~*|^~] /uri/ { … }
= starting with means an exact match
^~ starting with a certain Starting with a regular string, it can be understood as matching the url path. nginx does not encode the URL, so the request is /static/20%/aa, which can be ruled by the rule^~ /static/ /aa matches (note the space).
~ The beginning of means case-sensitive regular matching
~* The beginning of means case-insensitive regular matching
!~ and !~* are case-sensitive respectively does not match and case-insensitive does not match ’s regular
/ universal matching, any request will be matched.
In the case of multiple location configurations, the matching order is (comes from reference materials, not yet verified, just try it and you will know, don’t be rigid, just for reference):
First match =, secondly match^ ~, followed by regular matching in order in the file, and finally / universal matching. When a match is successful, the matching is stopped and the request is processed according to the current matching rules. Example, there are the following matching rules:
location = / {
   #规则A
}
location = /login {
   #规则B
}
location ^~ /static/ {
   #规则C
}
location ~ \.(gif|jpg|png|js|css)$ {
   #规则D
}
location ~* \.png$ {
   #规则E
}
location !~ \.xhtml$ {
   #规则F
}
location !~* \.xhtml$ {
   #规则G
}
location / {
   #规则H
}

Then the effect is as follows:
Visit the root directory/, for example, http://localhost/ will match rule A
http://localhost/login will match rule B, http://localhost/register will match rule H
when visiting http://localhost/static/a.html and will match rule C
when visiting http: //localhost/a.gif, http://localhost/b.jpg will match rule D and rule E, but the order of rule D takes precedence and rule E has no effect, while http://localhost/static/c.png Rule C is matched first
When accessing http://localhost/a.PNG, rule E is matched, but rule D is not matched, because rule E is not case-sensitive.
Visiting http://localhost/a.xhtml will not match rule F and rule G. http://localhost/a.XHTML will not match rule G because it is not case-sensitive. Rule F and Rule G belong to the elimination method, which conforms to the matching rules but will not be matched, so think about where they will be used in actual applications.
Visit http://localhost/category/id/1111 and finally match rule H. Because none of the above rules match, nginx should forward the request to the back-end application server at this time, such as FastCGI (php), tomcat (jsp), nginx exists as a direction proxy server.
So in actual use, I personally feel that there are at least three matching rule definitions, as follows:
#直接匹配网站根,通过域名访问网站首页比较频繁,使用这个会加速处理,官网如是说。
#这里是直接转发给后端应用服务器了,也可以是一个静态首页
# 第一个必选规则
location = / {
    proxy_pass http://tomcat:8080/index
}
 
# 第二个必选规则是处理静态文件请求,这是nginx作为http服务器的强项
# 有两种配置模式,目录匹配或后缀匹配,任选其一或搭配使用
location ^~ /static/ {
    root /webroot/static/;
}
location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
    root /webroot/res/;
}
 
#第三个规则就是通用规则,用来转发动态请求到后端应用服务器
#非静态文件请求就默认是动态请求,自己根据实际把握
#毕竟目前的一些框架的流行,带.php,.jsp后缀的情况很少了
location / {
    proxy_pass http://tomcat:8080/
}

Other information that has not been tested:
3. ReWrite syntax
last – basically All use this Flag.
break - Abort Rewirte and no longer continue matching
redirect - Return HTTP status 302 of temporary redirection
permanent - Return HTTP status 301 of permanent redirection
Note: The biggest difference between last and break is
- break is to terminate the rewrite detection of the current location, and no longer perform location matching - last is to terminate the rewrite detection of the current location, but will continue to retry location matching and process the rewrite rules in the block
1. The following is Expressions that can be used to determine:
-f and !-f are used to determine whether a file exists
-d and !-d are used to determine whether a directory exists
-e and !-e are used to determine whether a file or directory exists
-x and !-x are used to determine whether the file is executable
2. The following are global variables that can be used for judgment
$args #This variable is equal to the parameters in the request line.
$content_length #Content-length field in the request header.
$content_type #Content-Type field in the request header.
$document_root #The current request is the value specified in the root directive.
$host #Request host header field, otherwise it is the server name.
$http_user_agent #Client agent information
$http_cookie #Client cookie information
$limit_rate #This variable can limit the connection rate.
$request_body_file #The temporary file name of the client request body information.
$request_method #The action requested by the client, usually GET or POST.
$remote_addr #IP address of the client.
$remote_port #Port of the client.
$remote_user #Username that has been verified by Auth Basic Module.
$request_filename #The file path of the current request, generated by the root or alias directive and URI request.
$query_string #Same as $args.
$scheme #HTTP methods (like http, https).
$server_protocol #The protocol used by the request, usually HTTP/1.0 or HTTP/1.1.
$server_addr #Server address, this value can be determined after completing a system call.
$server_name #Server name.
$server_port #The port number where the request reaches the server.
$request_uri #Contains the original URI of the request parameters, excluding the host name, such as: "/foo/bar.php?arg=baz".
$uri #The current URI without request parameters, $uri does not contain the host name, such as "/foo/bar.html".
$document_uri # is the same as $uri. Example: http://localhost:88/test1/test2/test.php
$host:localhost
$server_port:88
$request_uri:http://localhost:88/test1/test2/test.php
$document_uri:/test1/test2/test.php
$document_root:D:nginx/html
$request_filename:D:nginx/html/test1/test2/test.php
4. Redirect syntax
Convert multiple directories into parameters
abc.domian.com/sort/2 => abc.domian.com/index.php?act=sort&name=abc&id=2
1.                                                                                                      ($host ~* (.*).domain.com) {
2. set $sub_name $1;
3. rewrite ^/sort/(d+)/?$ /index.php?act=sort&cid=$sub_name&id=$1 last;
4.                                                                                                                                                                                                           sort/sort/(d+)/?$ /index.php? ; /xxxx?id=1234561.                                                                     ^/(d+)/(.+)/ /$2?id=$1 last;

For example, the following setting nginx redirects to the /nginx-ie directory when the user uses ie:
1. if ($http_user_agent ~ MSIE) {
2.​​​​
rewrite ^(.*)$ /nginx-ie/$1 break;3. 
}The directory automatically adds "/"
1.}
if (-d $request_filename){
2.​​​​rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
3.}
htaccess prohibited1.  
location ~/.ht {
2.​​​​​​ Deny all;
3. }
Prohibit multiple directories1. Location ~ ^/(cron|templates)/ {
2.
                                                   Deny all;3. Break;
4. }Prohibit files starting with /dataYou can prohibit .log.txt and other requests in multi-level directories under /data/;
1. Location ~ ^/data {
2.​​​​​ Deny all;
3. }
Block a single directory
Cannot prohibit .log.txt request
1. Location /searchword/cron/ {2.​​​​
​ Deny all;3.
}Block a single file
1. Location ~ /data/sql/data.sql {
2.​​​​​​ Deny all;
3. }
Set the expiration time for favicon.ico and robots.txt; Here, favicon.ico is 99 days, robots.txt is 7 days, and no 404 error log is recorded
1.
location ~(favicon.ico) {
2.​​​​​​​ Log_not_found off;
3. expires 99d;
4. break;
5. }
6.
7. Location ~(robots.txt) {
8. Log_not_found off;
9. expires 7d;
10. break;
location ^~ /html/scripts/loadhead_1.js {2.
                                                    access_log off;
3.                                                                                                                                                                                                                                                                 root /opt/lampp/htdocs/web; 600;
5. break;
6. }
File anti-hotlinking and set expiration timeThe return 412 here is a custom http status code, the default is 403, which is convenient for finding the correct hotlinking request"rewrite ^/ http://leech. c1gstudio.com/leech.gif;"Show an anti-hotlink picture"access_log off;"Do not record access logs, reduce stress"expires 3d" Browser cache of all files for 3 days
1.
​​​​


location ~* ^.+.(jpg|jpeg|gif|png|swf|rar|zip|css|js)$ {
2.valid_referers none blocked *.c1gstudio.com *.c1gstudio.net localhost 208.97.167.194;
3.   if ($invalid_referer) {
4.                                    rewrite ^/ http://leech.c1gstudio.com/leech.gif;5. Return 412;
6. break;
7.                                access_log off;9.
root /opt/lampp/htdocs/web;10. expires 3d;
11. Only fixed IP access is allowed website and add the password
1.                                                                                                                     /opt/htdocs/www;2.
allow 208.97.167.194;3.
allow 222.33.1.2;
4. allow 231.152.49.4;
5. deny all;
6. auth_basic "C1G_ADMIN";
7.auth_basic_user_file htpasswd;
Convert files in multi-level directories into one file to enhance seo effect
/job-123-456-789.html points to /job/123/456/789.html
1. rewrite ^/job-([0-9]+)-([0-9]+)-([0-9]+).html$ /job/$1/$2/jobshow_$3.html last;
Point a folder in the root directory to the second-level directory
For example, /shanghaijob/ points to /area/shanghai/
If you change last to permanent, the browser address bar will show /location/shanghai/
1. ​​​​rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2 last;
A problem with the above example is that it will not match when accessing /shanghai
1 .        rewrite ^/([0-9a-z]+)job$ /area/$1/ last;
2.   rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2 last;
In this way, /shanghai can also be accessed, but the relative link in the page cannot be used,
such as The real address of ./list_1.html is /area /shanghia/list_1.html and will become /list_1.html, making it inaccessible.
Then it won’t work if I add automatic jump
(-d $request_filename) It has a condition that it must be a real directory, but my rewrite is not, so it has no effect
1.​​​​​ if (-d $request_filename){
2.​​​​rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
3.   }
After knowing the reason, it will be easier to handle, let me Jump manually
1. rewrite ^/([0-9a-z]+)job$ /$1job/ permanent;
2.​​​​rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2 last;
Redirect when files and directories do not exist:
1.​​​​ if (!-e $request_filename) {
2.   proxy_pass http://127.0.0.1;
3.   }
Domain name jump
1.     server
2.          {
3.                  listen       80;
4.                  server_name  jump.c1gstudio.com;
5.                  index index.html index.htm index.php;
6.                  root  /opt/lampp/htdocs/www;
7.                  rewrite ^/ http://www.c1gstudio.com/;
8.                  access_log  off;
9.          }
多域名转向
1.     server_name  www.c1gstudio.com www.c1gstudio.net;
2.                  index index.html index.htm index.php;
3.                  root  /opt/lampp/htdocs;
4.     if ($host ~ "c1gstudio.net") {
5.     rewrite ^(.*) http://www.c1gstudio.com$1 permanent;
6.     }
三级域名跳转
1.     if ($http_host ~* "^(.*).i.c1gstudio.com$") {
2.     rewrite ^(.*) http://top.yingjiesheng.com$1;
3.     break;
4.     }
域名镜向
1. server
2. {
3.                             80;                                                                                                                                 through        through out out out out out Out Out Out Out Out over into ’ over into ’s ’ s ​ ​ ​ ​ ’ through out out ’ s ​ ’ ’ back ​ ’ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ behalf ​ ​ ​ ​ ​ ​ ” ” “ server_name ” mirror.c1gstudio.com;
5. в index index.html index.htm index.php;6. Root /opt/lampP/htdocs/www ;
7.
                                                                                                                                                                  . access_log off;
9. } The above introduces the location configuration of nginx, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn