nginx配置文件-流量控制-域名跳转url重定向及https跳转问题

一、域名跳转方法 rewrite 和 return

Don’t feel bad here, it’s easy to get confused with regular expressions. In fact, it’s so easy to do that we should make an effort to keep them neat and clean. Quite simply, don’t add cruft.
BAD:

rewrite ^/(.*)$ http://example.com/$1 permanent;

GOOD:

rewrite ^ http://example.com$request_uri? permanent;

BETTER:

return 301 http://example.com$request_uri;

Look at the above. Then back here. Then up, and back here. OK. The first rewrite captures the full URI minus the first slash. By using the built-in variable $request_uri we can effectively avoid doing any capturing or matching at all.


return 语义更加明确,『到此为止』,结果就是 301 了。
正如你所说,正则匹配的性能损失;文中末尾也解释了『BAD』和 『GOOD』的区别

二、http域名跳转

跳转到本主机域名还是其他网站域名,都没有问题,不会报错。

server {
    listen 80;
    server_name .myolddomain.se;
    return 301 http://www.mynewdomain.se$request_uri;
}

三、https域名跳转

只能在本机配置的https域名中跳转,无法跳转到别家公司的https网站。因为https连接时,事先会读取网站证书。跳转的网站域名和本机提供的网站证书不匹配,导致浏览器报错。只能调转到本机的其他https网站,因为其他的https网站域名,本机已经提供了证书。

3.1 一个ip多个https网站

如果浏览器支持 TLS SNI 扩展:使用nginx -V 命令可以查看

server {
    listen X.X.X.X:443 ssl;
    ssl_certificate /path/to/myolddomain.cert;
    ssl_certificate_key /path/to/myolddomain.key;
    server_name .myolddomain.se;
    return 301 https://www.mynewdomain.se$request_uri;
}


server {
    listen X.X.X.X:443 ssl;
    ssl_certificate /path/to/mynewdomain.cert;
    ssl_certificate_key /path/to/mynewdomain.key;
    server_name .mynewdomain.se;

    [ ... ] # Your stuff

}

如果证书已经包含多个域名:

ssl_certificate /path/to/domain.cert;
ssl_certificate_key /path/to/domain.key;


server {
    listen X.X.X.X:443;
    server_name .myolddomain.se;
    return 301 https://www.mynewdomain.se$request_uri;
}


server {
    listen X.X.X.X:443;
    server_name .mynewdomain.se;

    [ ... ] # Your stuff

}

3.2不同ip多个https网站

server {
    listen X.X.X.X:443 ssl;
    ssl_certificate /path/to/myolddomain.cert;
    ssl_certificate_key /path/to/myolddomain.key;
    server_name .myolddomain.se;
    return 301 https://www.mynewdomain.se$request_uri;
}

server {
    listen Y.Y.Y.Y:443 ssl;
    ssl_certificate /path/to/mynewdomain.cert;
    ssl_certificate_key /path/to/mynewdomain.key;
    server_name .mynewdomain.se;

    [ ... ] # Your stuff

}

 

 

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments