Nginx 一些常用的URL 重写方法

url重写应该不陌生,不管是SEO URL 伪静态的需要,还是在非常流行的wordpress里,重写无处不在。

1. Apache 的写法

RewriteCond  %{HTTP_HOST}  nginx.org
RewriteRule  (.*)  http://www.nginx.org$1


Nginx 可以对应写成:


server {
    listen       80;
    server_name  www.nginx.org  nginx.org;
    if ($http_host = nginx.org) {
        rewrite  (.*)  http://www.nginx.org$1;
    }
    ...
}

Nginx 作者更建议的方法是:

server {
    listen       80;
    server_name  nginx.org;
    rewrite   ^  http://www.nginx.org$request_uri?;
}

server {
    listen       80;
    server_name  www.nginx.org;
    ...
}

F&Q

1. 请教一下,nginxrewrite规则怎么写?

比如将 http://http://www.oschina.net/222.html rewrite http://http://www.oschina.net/222.htm

location ~ .*.(html)$

          {

           rewrite ^(.*).html  $1.htm permanent;

         }

2. 下面url要怎么写rewrite?

www.aaa.com/search/?wd=搜索内容  ==> www.aaa.com/searchpage?keyword=搜索内容


location ~ ^/search/ { 

            rewrite (.*) /searchpage$1 ; 

3. 请求的url如下 /item/12345/index.html 重定向到/item/12/12345/index.html

规则就是id1000,如果小于id小于1000,则为/item/0/id/index.html

不知道说清楚没有,这个rewrite规则该怎么写啊?


刚看了文档,似乎可以

http://wiki.nginx.org/HttpRewriteModule

/photos/123456  -> /path/to/photos/12/1234/123456.png

rewrite  "/photos/([0-9] {2})([0-9] {2})([0-9] {2})" /path/to/photos/$1/$1$2/$1$2$3.png;

备注:

有一个工具是apache htaccess 文件转 nginx rewrite:

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

原文地址:https://www.cnblogs.com/tonykan/p/3508577.html