Nginx server configuration and routing rewrite related

Source: Internet
Author: User
Tags browser cache domian

File name example.conf server {#监听的端口号

Listen 80;

           
#域名
server_name www.example.com *.example.com;               #指定目录某个目录的父目录, Root d:/www; #指定404页面 Error_page 404/404.php;
#location模块当其他都匹配不到的时候才匹配 '/' #根目录下,location/{
#配置默认页
Index index.php
#nginx路由重写示例, if multiple files can be configured
rewrite ^/(\w+) \.html/$/$1.php;
rewrite ^/(\w+)/(\w+)/$/$1/$2.php;
} #根目录下的demo目录
Location/demo {
#自动索引, auto-address, that is, no default page, display the current directory autoindex on;           
} #php文件解析location ~ \.php$ {fastcgi_pass 127.0.0.1:9000;            Fastcgi_index index.php;            Fastcgi_param script_filename $document _root$fastcgi_script_name;  Include fcgi.conf;  } #log记录, you can use off to close access_log Logs/location-access.log main;
}#代理服务器server {
listen 8080;   Root D:/www/demo; Location/{
index 8080.html;
  }
}#除gif, JPG, PNG format, other full agent to 8080 ports
server {location    /{        proxy_pass http://localhost:8080/;    }    Location ~ \. (gif|jpg|png) $ {        root/data/images;    }}

Nginx Rewrite rules related directives
Nginx rewrite rules related directives have if, rewrite, set, return, break, etc., where rewrite is the most critical instruction. A simple nginx rewrite rule syntax is as follows:

Rewrite ^/b/(. *) \.html/play.php?video=$1 break;

If you add an if statement, the example is as follows:

if (!-f $request _filename)

Rewrite ^/img/(. *) $/site/$host/images/$1 last;

Comparison between Nginx and Apache's rewrite rule examples

Simple Nginx and Apache rewrite rules are not very different, basically can be fully compatible. For example:

Apache Rewrite Rules:

Rewriterule ^/(mianshi|xianjing)/$/zl/index.php?name=$1 [L]

Rewriterule ^/ceshi/$/zl/ceshi.php [L]

Rewriterule ^/(Mianshi) _ ([a-za-z]+)/$/zl/index.php?name=$1_$2 [L]

Rewriterule ^/PINGCE ([0-9]*)/$/zl/pingce.php?id=$1 [L]

Nginx Rewrite Rules:

Rewrite ^/(mianshi|xianjing)/$/zl/index.php?name=$1 last;

Rewrite ^/ceshi/$/zl/ceshi.php last;

Rewrite ^/(Mianshi) _ ([a-za-z]+)/$/zl/index.php?name=$1_$2 last;

Rewrite ^/PINGCE ([0-9]*)/$/zl/pingce.php?id=$1 last;

As can be seen from the above example, Apache rewrite rules changed to Nginx rewrite rules, in fact, very simple: Apache rewriterule instructions for Nginx rewrite instructions, Apache's [L] The tag is replaced with the last tag of Nginx, and the content in the middle is unchanged.

If Apache's rewrite rules are changed to Nginx rewrite rules, use the NGINX-T command to check that the nginx.conf configuration file has a syntax error, then you can try to enclose the condition in quotation marks. For example, the Nginx rewrite rule will report a syntax error:

Rewrite ^/([0-9]{5}). html$/x.jsp?id=$1 last;

The quotation marks are correct:
Rewrite "^/([0-9]{5}). html$"/x.jsp?id=$1 last;

The rewrite rules for Apache and Nginx have subtle differences in URL jumps:

Apache Rewrite Rules:
Rewriterule ^/html/tagindex/([a-za-z]+)/.*$/$1/[r=301,l]

Nginx Rewrite Rules:
Rewrite ^/html/tagindex/([a-za-z]+)/.*$/http $host/$1/permanent;

In the above example, we notice that the "http://$host" is added to the replacement string of the Nginx Rewrite rule, which is required in Nginx.

In addition, the rewrite rules for Apache and Nginx also differ in variable names, such as:

Apache Rewrite Rules:
Rewriterule ^/user/login/$/user/login.php?login=1&forward=http://%{http_host} [L]

Nginx Rewrite Rules:
Rewrite ^/user/login/$/user/login.php?login=1&forward=http://$host last;

Apache and Nginx Rewrite some functions of the same or similar directive, tag correspondence:

Apache's Rewritecond instruction corresponds to Nginx's if command;
Apache's Rewriterule instruction corresponds to Nginx's rewrite instruction;
Apache's [R] tag corresponds to Nginx's redirect tag;
Apache's [P] tag corresponds to the last tag of Nginx;
Apache's [r,l] tag corresponds to Nginx's redirect tag;
Apache's [p,l] tag corresponds to the last tag of Nginx;
Apache's [pt,l] tag corresponds to the last tag of Nginx;

Allow the specified domain name to access this site, other domain names are redirected to Http://www.aaa.com

Apache Rewrite Rules:
Rewritecond%{http_host} ^ (. *?) \.domain\.com$
Rewritecond%{http_host}!^qita\.domain\.com$
Rewritecond%{document_root}/market/%1/index.htm-f
Rewriterule ^/wu/$/market/%1/index.htm [L]

Nginx if directive does not support nesting, also does not support and, or and so on multi-condition match, compared to the Apache Rewritecond, appears to be troublesome, but, we can implement this example through the next page of Nginx configuration notation:

Nginx Rewrite Rules:
if ($host ~* ^ (. *?) \.domain\.com$) set $var _wupin_city $;
Set $var _wupin ' 1′;

if ($host ~* ^qita\.domain\.com$)

Set $var _wupin ' 0′;

if (!-f $document _root/market/$var _wupin_city/index.htm)

Set $var _wupin ' 0′;

if ($var _wupin ~ ' 1′)

Rewrite ^/wu/$/market/$var _wupin_city/index.htm last;
}

The syntax of rewrite

Syntax: rewrite regex replacement flag

Default: None

Scope: server, location, if

This directive changes URI in accordance with the regular expression and the replacement string. Directives is carried out in order of appearance in the configuration file.

This instruction changes the URI based on an expression, or modifies a string. Directives are executed according to the order in the configuration file.

Being aware that the rewrite regex is only matches the relative path instead of the absolute URL. If you are want to match the hostname, you should use a if condition, like so:

Note that the rewrite expression is valid only for relative paths. If you want to pair the host name, you should use the IF statement.

rewrite just will rewrite the path part of the east, will not change the user's input parameters, so here if the rules, you do not have to care about the user in the browser input parameters, rewrite will be automatically added , so we just add a? Number and a small parameter that we want to ***https=1 on the back.

Nginx's rewrite rule reference:

    1. ~ For case-sensitive matching
    2. ~* for case-insensitive matching
    3. !~ and!~* are case insensitive and case insensitive
    1. -F and!-f to determine if a file exists
    2. -D and!-d to determine if a directory exists
    3. -E and!-e to determine if a file or directory exists
    4. -X and!-x to determine if a file is executable
    1. Last equivalent to Apache in the [L] mark, indicating the completion of rewrite, hehe this should be the most common
    2. Break terminates the match and no longer matches the following rule
    3. REDIRECT Returns 302 the temporary redirect Address bar displays the address after the jump
    4. Permanent return 301 Permanent Redirect Address bar displays the address after the jump
    1. $args
    2. $content _length
    3. $content _type
    4. $document _root
    5. $document _uri
    6. $host
    7. $http _user_agent
    8. $http _cookie
    9. $limit _rate
    10. $request _body_file
    11. $request _method
    12. $remote _addr
    13. $remote _port
    14. $remote _user
    15. $request _filename
    16. $request _uri
    17. $query _string
    18. $scheme
    19. $server _protocol
    20. $server _addr
    21. $server _name
    22. $server _port
    23. $uri

Examples of combining qeephp

    1. if (!-d $request _filename) {
    2. Rewrite ^/([a-z-a-z]+)/([a-z-a-z]+)/? (. *) $/index.php?namespace=user&controller=$1&action=$2&$3 last;
    3. Rewrite ^/([a-z-a-z]+)/?$/index.php?namespace=user&controller=$1 last;
    4. Break

Convert multiple catalogs into parameters
ABC.DOMIAN.COM/SORT/2 = abc.domian.com/index.php?act=sort&name=abc&id=2

    1. if ($host ~* (. *) \.domain\.com) {
    2. Set $sub _name $;
    3. Rewrite ^/sort\/(\d+) \/?$/index.php?act=sort&cid= $sub _name&id=$1 last;
    4. }

Catalog Swap
/123456/xxxx-/xxxx?id=123456

    1. Rewrite ^/(\d+)/(. +)//$2?id=$1 last;

For example, the following setting Nginx is redirected to the/nginx-ie directory using IE's use of the user:

    1. if ($http _user_agent ~ MSIE) {
    2. Rewrite ^ (. *) $/nginx-ie/$1 break;
    3. }

Catalog automatically add "/"

    1. if (-D $request _filename) {
    2. Rewrite ^/(. *) ([^/]) $/HTTP $host/$1$2/permanent;
    3. }

Prohibit htaccess

    1. Location ~/\.ht {
    2. Deny all;
    3. }

Disallow multiple directories

    1. Location ~ ^/(cron|templates)/{
    2. Deny all;
    3. Break
    4. }

Prohibit files that start with/data
Can prohibit/data/under the multilevel directory. Log.txt and other requests;

    1. Location ~ ^/data {
    2. Deny all;
    3. }

Prohibit a single directory
Cannot forbid. Log.txt can request

    1. location/searchword/cron/{
    2. Deny all;
    3. }

Prohibit individual files

    1. Location ~/data/sql/data.sql {
    2. Deny all;
    3. }

Set expiration time for Favicon.ico and robots.txt;
Here is favicon.ico for 99 days, robots.txt for 7 days does not log 404 error logs

    1. Location ~ (favicon.ico) {
    2. Log_not_found off;
    3. Expires 99d;
    4. Break
    5. }
    6. Location ~ (robots.txt) {
    7. Log_not_found off;
    8. Expires 7d;
    9. Break
    10. }

Sets the expiration time of a file, which is 600 seconds, and does not log access logs

    1. Location ^~/html/scripts/loadhead_1.js {
    2. Access_log off;
    3. Root/opt/lampp/htdocs/web;
    4. Expires 600;
    5. Break
    6. }

File anti-hotlinking and set expiration time
The return 412 here is a custom HTTP status code with a default of 403, which makes it easy to find the correct hotlinking request.
"Rewrite ^/http://leech.divmy.com/leech.gif;" Show a picture of the anti-theft chain
"Access_log off;" Reduce stress by not logging access logs
"Expires 3d" All files 3-day browser cache

    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.divmy.com/leech.gif;
    5. return 412;
    6. Break
    7. }
    8. Access_log off;
    9. Root/opt/lampp/htdocs/web;
    10. Expires 3d;
    11. Break
    12. }

Only allow fixed IP access to the website, plus a password

    1. root/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 from a multilevel directory to a file to enhance SEO results
/job-123-456-789.html Point 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 under the root directory to a level 2 directory
such as/Shanghaijob/point to/area/Shanghai/
If you change last to permanent, then the browser address bar is/location/shanghai/

    1. Rewrite ^/([0-9a-z]+) job/(. *) $/area/$1/$2 last;

One of the problems with the above example is that access to/shanghai will not match

    1. Rewrite ^/([0-9a-z]+) job$/area/$1/last;
    2. Rewrite ^/([0-9a-z]+) job/(. *) $/area/$1/$2 last;

This/shanghai can also be accessed, but the relative links in the page are not available,
If the real address of the./list_1.html is/area/shanghia/list_1.html will become/list_1.html, which leads to inaccessible.

Well, I'm not going to add the auto jump.
(-D $request _filename) It has a condition that is required for the real directory, and my rewrite is not, so no effect

    1. if (-D $request _filename) {
    2. Rewrite ^/(. *) ([^/]) $/HTTP $host/$1$2/permanent;
    3. }

Know the reason after the good, let me manually jump

    1. Rewrite ^/([0-9a-z]+) job$/$1job/permanent;
    2. Rewrite ^/([0-9a-z]+) job/(. *) $/area/$1/$2 last;

Redirects when files and directories do not exist:

    1. if (!-e $request _filename) {
    2. Proxy_pass http://127.0.0.1;
    3. }

Domain Jump

    1. Server
    2. {
    3. Listen 80;
    4. server_name jump.88dgw.com;
    5. Index index.html index.htm index.php;
    6. root/opt/lampp/htdocs/www;
    7. Rewrite ^/http://www.88dgw.com/;
    8. Access_log off;
    9. }

Multi-domain Steering

    1. server_name www.7oom.com/www.divmy.com/;
    2. Index index.html index.htm index.php;
    3. Root/opt/lampp/htdocs;
    4. if ($host ~ "C1gstudio\.net") {
    5. Rewrite ^ (. *) http://www.7oom.com$1/permanent;
    6. }

Three-level domain jump

    1. if ($http _host ~* "^ (. *) \.i\.c1gstudio\.com$") {
    2. Rewrite ^ (. *) http://top.88dgw.com$1/;
    3. Break
    4. }

The Domain name Mirror

    1. Server
    2. {
    3. Listen 80;
    4. server_name mirror.c1gstudio.com;
    5. Index index.html index.htm index.php;
    6. root/opt/lampp/htdocs/www;
    7. Rewrite ^/(. *) http://www.divmy.com/$1 last;
    8. Access_log off;
    9. }

A subdirectory for the mirror

    1. Location ^~/zhaopinhui {
    2. Rewrite ^.+ http://zph.divmy.com/last;
    3. Break
    4. }

Discuz Ucenter Home (uchome) rewrite

    1. Rewrite ^/(space|network)-(. +) \.html$/$1.php?rewrite=$2 last;
    2. Rewrite ^/(space|network) \.html$/$1.php last;
    3. Rewrite ^/([0-9]+) $/space.php?uid=$1 last;

Discuz 7 Rewrite

    1. Rewrite ^ (. *)/archiver/((Fid|tid)-[\w\-]+\.html) $ $1/archiver/index.php?$2 last;
    2. Rewrite ^ (. *)/forum-([0-9]+)-([0-9]+] \.html$ $1/forumdisplay.php?fid=$2&page=$3 last;
    3. Rewrite ^ (. *)/thread-([0-9]+)-([0-9]+)-([0-9]+] \.html$ $1/viewthread.php?tid=$2&extra=page\%3d$4&page=$3 Last
    4. Rewrite ^ (. *)/profile-(USERNAME|UID)-(. +) \.html$ $1/viewpro.php?$2=$3 last;
    5. Rewrite ^ (. *)/space-(USERNAME|UID)-(. +) \.html$ $1/space.php?$2=$3 last;
    6. Rewrite ^ (. *)/tag-(. +) \.html$ $1/tag.php?name=$2 last;

Configure a domain name separately for a discuz section

    1. server_name bbs.c1gstudio.com news.c1gstudio.com;
    2. Location =/{
    3. if ($http _host ~ news\.divmy.com$) {
    4. Rewrite ^.+ http://news.divmy.com/forum-831-1.html last;
    5. Break
    6. }
    7. }

Discuz ucenter Avatar Rewrite optimization

    1. Location ^~/ucenter {
    2. Location ~. *\.php?$
    3. {
    4. #fastcgi_pass Unix:/tmp/php-cgi.sock;
    5. Fastcgi_pass 127.0.0.1:9000;
    6. Fastcgi_index index.php;
    7. Include fcgi.conf;
    8. }
    9. Location/ucenter/data/avatar {
    10. Log_not_found off;
    11. Access_log off;
    12. Location ~/(. *) _big\.jpg$ {
    13. Error_page 404/ucenter/images/noavatar_big.gif;
    14. }
    15. Location ~/(. *) _middle\.jpg$ {
    16. Error_page 404/ucenter/images/noavatar_middle.gif;
    17. }
    18. Location ~/(. *) _small\.jpg$ {
    19. Error_page 404/ucenter/images/noavatar_small.gif;
    20. }
    21. Expires 300;
    22. Break
    23. }
    24. }

Jspace rewrite

    1. Location ~. *\.php?$
    2. {
    3. #fastcgi_pass Unix:/tmp/php-cgi.sock;
    4. Fastcgi_pass 127.0.0.1:9000;
    5. Fastcgi_index index.php;
    6. Include fcgi.conf;
    7. }
    8. Location ~* ^/index.php/
    9. {
    10. Rewrite ^/index.php/(. *)/index.php?$1 break;
    11. Fastcgi_pass 127.0.0.1:9000;
    12. Fastcgi_index index.php;
    13. Include fcgi.conf;
    14. }

There is also a tool that can directly translate Apache rules into nginx rules.

http://www.anilcetin.com/convert-apache-htaccess-to-nginx/

Reference:

Http://wiki.nginx.org/NginxChsHttpRewriteModule

Http://blog.csdn.net/cnbird2008/archive/2009/08/04/4409620.aspx

http://www.divmy.com/

Nginx server configuration and routing rewrite related

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.