nginx伪静态配置rewrite重写url

这个困扰我将近一个星期的问题,百度了一个星期都没有找到我想要的答案,对于一个nginx小白的我来说真的是个烦人的问题,这一个星期里我都好几次想放弃,不过事实证明坚持下去是没有错的,好了话不多说进入正题:


首先打开我们的nginx配置文件:nginx.conf 找到server{...}这块,我的是这样的,

server {
        listen       80;
        server_name  www.chemistry.com chemistry.com;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;
        root   "E:/phpStudy/WWW/chemistry-smarty";
        location / {
            try_files $uri $uri/ /index.php?$query_string;
            index  index.html index.htm index.php l.php;
           autoindex  off;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
         #   proxy_pass   http://127.0.0.1:81;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ \.php(.*)$  {
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_split_path_info  ^((?U).+\.php)(/?.+)$;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            fastcgi_param  PATH_INFO  $fastcgi_path_info;
            fastcgi_param  PATH_TRANSLATED  $document_root$fastcgi_path_info;
            include        fastcgi_params;
        }

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }

要想实现伪静态,我这里用的是rewrite重定向url

rewrite语法:rewrite regex replacement flag;

regex:是你要匹配url地址的正则(正则表达式我在这里就不介绍了)

replacement:是你要重定向的url地址

flag:标志位,有以下几种:

  • last : 相当于Apache的[L]标记,表示完成rewrite,最常用
  • break : 停止执行当前虚拟主机的后续rewrite指令集
  • redirect : 返回302临时重定向,地址栏会显示跳转后的地址
  • permanent : 返回301永久重定向,地址栏会显示跳转后的地址

下面来对我的url重定向

server {
        listen       80;
        server_name  www.chemistry.com chemistry.com; 

        root   "E:/phpStudy/WWW/chemistry-smarty";
        location / {
            try_files $uri $uri/ /index.php?$query_string;
            rewrite  ^/resource/home/new-(\d+)\.html$ /resource/home/new-content.php?id=$1 last;
            index  index.html index.htm index.php l.php;
           autoindex  off;
        }

...

}

nginx伪静态配置rewrite重写url


要注意的是,匹配的和要重定向的文件都必须存在才能有用。

图片上所写的(\d+)匹配到的数字赋值给$1,这样就可以定向到对应的文件