Nginx Location, rewrite configuration summary

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Rule of grammar: location [=|~|~*|^~] /uri/ { … }
= At the beginning of that exact matching
^~ Beginning with a conventional URI beginning of the string, understood as the matching URL path. Nginx URL do not code, therefore the request is /static/20%/aa, can be matched to the rules /static//aa ^ ~ (note is empty).
~ At the beginning of that distinguish regular case matching
~* At the beginning of that does not distinguish between regular case matching
!~And! ~ * are case sensitive and case insensitive does not match the regular mismatch
/ General matching, any requests are matched to the.
Multiple location configuration in the case of matching order for (reference to, not the actual verification, try to know, do not need to worry about, for reference only):
The first match =, then the matching ^ ~, followed by regular file sequence matching, finally give / general matching. When successful matching time, stop the match, according to the current matching rule processing request.
For example, the following match rules:
location = / {
#Rule A
}
location = /login {
#Rule B
}
location ^~ /static/ {
#Rule C
}
location ~ \.(gif|jpg|png|js|css)$ {
#Rule D
}
location ~* \.png$ {
#Rule E
}
location !~ \.xhtml$ {
#Rule F
}
location !~* \.xhtml$ {
#Rule G
}
location / {
#Rule H
}
So the effect of the following:
Root access /, such as matching rules A
Access to the matching rule B, matching rule H
Access will match the rules of C
Access, the matching rules D and E, but the D order of priority rules, rule E does not play a role, but the priority is matched to the rules of C
Access is matching rule E, but not D E matching rules, because the rules are not case sensitive.
Access will not match the rules F and G, G does not match rule, because insensitive. Rule F, rule G belong to the elimination, in line with the matching rules but not to match, so think of practical applications where used.
Access is the final match to the rules of H, because it does not match the rules above, this time should be nginx forwarding requests to the backend application servers, such as FastCGI (PHP), Tomcat (JSP), nginx as the direction of the proxy server exists.


So in actual use, personally feel that there are at least three matching rule definition, as follows:
#The direct matching site root, the domain name to visit the website home page is more frequent, this will accelerate the process, official says.
#Here is directly transmitted to the back-end application server, but also can be a static page
# The first mandatory rules
location = / {
proxy_pass
}
# Second mandatory rules are static file request, this is the nginx as the HTTP server.
# There are two kinds of configuration mode, matching directory matching or suffix, choose one or with the use of
location ^~ /static/ {
root /webroot/static/;
}
location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
root /webroot/res/;
}
#The third rule is the general rule, used to forward requests to a back-end application server
#Non static file request default is dynamic request, according to the actual grasp yourself
#After all, some of the current framework of popular, with.Php,.Jsp suffix is rare.
location / {
proxy_pass
}


In the nginx proxy_pass configuration, if ^ ~ matching path in accordance with proxy_pass, should pay attention to the URL final /, when coupled with the /, equivalent to the absolute root path, nginx will not take part in the match the path location; if not, you will put the matching path parts are also give the agent walks.
location ^~ /static_js/
{
proxy_cache js_cache;
proxy_set_header Host js.test.com;
proxy_pass ;
}
If the above configuration, if the requested URL is http://servername/static_js/test.html
Will be acting as the
If such a configuration
location ^~ /static_js/
{
proxy_cache js_cache;
proxy_set_header Host js.test.com;
proxy_pass ;
}
It will be an agent to
Of course, we can realize / using the following rewrite function
location ^~ /static_js/
{
proxy_cache js_cache;
proxy_set_header Host js.test.com;
rewrite /static_js/(.+)$ /$1 break;
proxy_pass ;
}


Three, the ReWrite syntax

The nginx type is rewrite: rewrite regex replacement flag
Rewrite can be placed in the server, location and if module.

Nginx rewrite instruction execution sequence:

1 server blocks the execution of rewrite instructions (here refers to the block after the keyword server {} region surrounded by the other, XX blocklike)
2 implementation of location matching
3 selected location rewrite instruction
If one step URI is overridden, then re executes 1-3, until you find the real file
If the circulation of more than 10 times, or 500 Internal Server Error error

The four flag marker type:
last – The equivalent of Apache L
break – Suspend Rewirte, not to continue the match
redirect – Returns a temporary redirect HTTP status 302, equivalent to Apache in R
permanent – Returns a permanent redirect HTTP status 301, equivalent to Apache in R=301

1, The following is the expression can be used to judge:
-f and -f are used to determine whether a file exists!
-d and -d are used to determine whether there is a directory!
-e and -e are used to determine whether there! A file or directory
-x and -x are used to determine whether a document! Executable
2, The following can be used as a global variable judgment
An example:
$host: localhost
$server_port: 88
$request_uri:
$document_uri: /test1/test2/test.php
$document_root: D:\nginx/html
$request_filename: D:\nginx/html/test1/test2/test.php
Four, the Redirect syntax
server {
listen 80;
server_name start.igrow.cn;
index index.html index.php;
root html;
if ($http_host !~ "^star\.igrow\.cn$&quot {
rewrite ^(.*) redirect;
}
}
Five, the chain
location ~* \.(gif|jpg|swf)$ {
valid_referers none blocked start.igrow.cn sta.igrow.cn;
if ($invalid_referer) {
rewrite ^/ ;
}
}
Six, according to the document type setting expiration time
location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ {
if (-f $request_filename) {
expires 1h;
break;
}
}
Seven, to prohibit access to a directory
location ~* \.(txt|doc)${
root /data/www/wwwroot/linuxtone/test;
deny all;
}

Because the rewrite execution efficiency is low, usually is replaced by a return statement, such as:

rewrite (.*) $1;

Instead of

retrun 301 https://www.example.org$request_uri;


Some of the available global variables:

$args
$content_length
$content_type
$document_root
$document_uri
$host
$http_user_agent
$http_cookie
$limit_rate
$request_body_file
$request_method
$remote_addr
$remote_port
$remote_user
$request_filename
$request_uri
$query_string
$scheme
$server_protocol
$server_addr
$server_name
$server_port
$uri

The rewirite instance:

Multi directory into parameters
abc.domian.com/sort/2 => abc.domian.com/index.php?act=sort&name=abc&id=2
if ($host ~* (.*)\.domain\.com) {
set $sub_name $1;
rewrite ^/sort\/(\d+)\/?$ /index.php?act=sort&cid=$sub_name&id=$1 last;
}
Directory on the
/123456/xxxx -> /xxxx?id=123456
rewrite ^/(\d+)/(.+)//$2?id=$1 last;
For example, the following set nginx in the user with IE redirects to the /nginx-ie directory:
if ($http_user_agent ~ MSIE) {
rewrite ^(.*)$ /nginx-ie/$1 break;
}
Directory is automatically added"/"
if (-d $request_filename){
rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
}
Disable htaccess
location ~/\.ht {
deny all;
}
Multiple directory prohibited
location ~ ^/(cron|templates)/ {
deny all;
break;
}
Prohibited to /data at the beginning of the file
You can disable /data/ under multi-level directory.Log.txt request;
location ~ ^/data {
deny all;
}
No single directory
Cannot disable.Log.txt can request
location /searchword/cron/ {
deny all;
}
No single file
location ~ /data/sql/data.sql {
deny all;
}
Set an expiration time for favicon.ico and robots.txt;
Here is favicon.ico for 99 days, robots.txt for 7 days did not record 404 error log
location ~(favicon.ico) {
log_not_found off;
expires 99d;
break;
}
location ~(robots.txt) {
log_not_found off;
expires 7d;
break;
}
To set the expiration time of a file; here is 600 seconds, do not record access log
location ^~ /html/scripts/loadhead_1.js {
access_log off;
root /opt/lampp/htdocs/web;
expires 600;
break;
}
File anti Daolian and set the expiration time
Here the return 412 as a custom HTTP status code, the default is 403, convenient to find the correct link request
"rewrite ^/ ;"Display a security chain.
"access_log off;"Do not record access log, ease the pressure
"expires 3d"All file 3 days the browser cache
location ~* ^.+\.(jpg|jpeg|gif|png|swf|rar|zip|css|js)$ {
valid_referers none blocked *.c1gstudio.com *.c1gstudio.net localhost 208.97.167.194;
if ($invalid_referer) {
rewrite ^/ ;
return 412;
break;
}
access_log off;
root /opt/lampp/htdocs/web;
expires 3d;
break;
}
Only with a fixed IP access to the web site, and add a password
root /opt/htdocs/www;
allow 208.97.167.194;
allow 222.33.1.2;
allow 231.152.49.4;
deny all;
auth_basic "C1G_ADMIN";
auth_basic_user_file htpasswd;
The multi-level directory files into one file, the enhanced SEO effect
/Job-123-456-789.html points to/job/123/456/789.html
rewrite ^/job-([0-9]+)-([0-9]+)-([0-9]+)\.html$ /job/$1/$2/jobshow_$3.html last;
The root directory of a folder to 2 directory
As /shanghaijob/ points /area/shanghai/
If you change last to permanent, then the browser address bar is significant/location/shanghai/
rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2 last;
The above example has a problem is access to /shanghai will not match
rewrite ^/([0-9a-z]+)job$ /area/$1/ last;
rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2 last;
This /shanghai can be visited, but the relative links page cannot be used,
Such as./list_1.html address is /area/shanghia/list_1.html will become /list_1.html, leading to cannot access.
Then I add automatically jump is not.
(-d $request_filename)It is a condition which is required for the real catalogue, and my rewrite is not, so there is no effect
if (-d $request_filename){
rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
}
Know the right reason, let me hand jump.
rewrite ^/([0-9a-z]+)job$ /$1job/ permanent;
rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2 last;
When the file and directory does not exist redirection:
if (!-e $request_filename) {
proxy_pass ;
}
Domain jump
server
{
listen 80;
server_name jump.c1gstudio.com;
index index.html index.htm index.php;
root /opt/lampp/htdocs/www;
rewrite ^/ ;
access_log off;
}
Multi domain steering
server_name www.c1gstudio.com www.c1gstudio.net;
index index.html index.htm index.php;
root /opt/lampp/htdocs;
if ($host ~ "c1gstudio\.net") {
rewrite ^(.*) $1 permanent;
}
The three level domain jump
if ($http_host ~* "^(.*)\.i\.c1gstudio\.com$") {
rewrite ^(.*) $1;
break;
}
Domain name mirror
server
{
listen 80;
server_name mirror.c1gstudio.com;
index index.html index.htm index.php;
root /opt/lampp/htdocs/www;
rewrite ^/(.*) $1 last;
access_log off;
}
A subdirectory as mirror
location ^~ /zhaopinhui {
rewrite ^.+ last;
break;
}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Simon at February 27, 2014 - 1:51 PM