nginx url重写

[root@web01 www]# cat /app/server/nginx/conf/vhosts/default.conf
server {
    listen 80 default_server;
    server_name localhost;
    root /app/www;
    index index.php index.htm index.html;
    rewrite /last.html /index.html last;
    rewrite /break.html /index.html break;
    rewrite /redirect.html /index.html redirect;#302临时重定向
    rewrite /permanent.html /index.html permanent;#301永久重定向
    rewrite ^/html/(.+?).html$ /post/$1.html permanent;
    location ~ .*.(php|php5)?$
    {
       #fastcgi_pass  unix:/tmp/php-cgi.sock;
        fastcgi_pass  127.0.0.1:9000;
    fastcgi_index index.php;
    include fastcgi.conf;
    }
    access_log  /app/log/nginx/access/default.log;
}
[root@web01 www]# tree /app/www/
/app/www/
├── index.html
├── index.php
└── post
    └── test.html

1 directory, 3 files
[root@web01 www]# cat /app/www/index.html 
clnking@163.com
[root@web01 www]# cat /app/www/post/test.html 
post/test.html
[root@web01 www]# curl 192.168.1.24/last.html
clnking@163.com
[root@web01 www]# curl --head 192.168.1.24/last.html
HTTP/1.1 200 OK
Server: nginx/1.4.4
Date: Tue, 02 Aug 2016 01:53:10 GMT
Content-Type: text/html
Content-Length: 16
Last-Modified: Mon, 18 Jul 2016 11:46:03 GMT
Connection: keep-alive
ETag: "578cc17b-10"
Accept-Ranges: bytes
[root@web01 www]# curl 192.168.1.24/break.html
clnking@163.com
[root@web01 www]# curl --head 192.168.1.24/break.html
HTTP/1.1 200 OK
Server: nginx/1.4.4
Date: Tue, 02 Aug 2016 01:54:40 GMT
Content-Type: text/html
Content-Length: 16
Last-Modified: Mon, 18 Jul 2016 11:46:03 GMT
Connection: keep-alive
ETag: "578cc17b-10"
Accept-Ranges: bytes
[root@web01 www]# curl 192.168.1.24/redirect.html
<html>
<head><title>302 Found</title></head>
<body bgcolor="white">
<center><h1>302 Found</h1></center>
<hr><center>nginx/1.4.4</center>
</body>
</html>

[root@web01 www]# curl 192.168.1.24/permanent.html
<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.4.4</center>
</body>
</html>

[root@web01 www]# curl 192.168.1.24/html/test.html
<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.4.4</center>
</body>
</html>

 注意:因为301和302不能简单的只返回状态码,还必须有重定向的URL,这就是return指令无法返回301,302的原因了;

 301重定向可以说是网页更改地址后对搜索引擎最好友好的方法,它代表永久性转移。
一般来说,只要不是暂时搬移的情况,我们都建议使用301来做转址。 而且从搜索引擎优化的角度来看,301重定向是网址进行重定向最为可行的一种办法。当网站的域名发生变更后,搜索引擎只对新网址进行索引,
同时又会把旧地址下原有的外部链接如数转移到新地址下,从而不会让网站的排名因为网址变更而收到丝毫影响。因此,
在使用301永久性重定向命令让多个域名指向网站主域时, 亦不会对网站的排名产生任何负面影响。 【301与302转向的区别】 实施301后,新网址完全继承旧网址,旧网址的排名等完全清零。 实施302后,对旧网址没有影响,但新网址不会有排名。
原文地址:https://www.cnblogs.com/bass6/p/5732689.html