问题原文
原帖链接 · gregory · CC BY-SA 3.0
I'm trying to migrate a site from HTTP to HTTPS, however, my nginx (version: 1.10.3) config seems not to be working.
The following behavior is desired:
http://www.example.com/path/to/contentshould redirect tohttps://example.com/path/to/contenthttp://example.com/path/to/contentshould redirect tohttps://example.com/path/to/contenthttps://www.example.com/path/to/contentshould redirect tohttps://example.com/path/to/content
With my current config browsers wont connect to the site using HTTPS:
server {
listen 80;
listen [::]:80;
server_name www.example.com example.com;
# redirects both www and non-www to https
rewrite ^(.*) https://www.example.com$1 permanent;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com;
# redirects non-www to www
rewrite ^(.*) https://www.example.com$1 permanent;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
include snippets/ssl-example.com.conf;
include snippets/ssl-params.conf;
charset utf-8;
# rest of my config
}
- What do I have to change to achieve the above mentioned behavior?
- Is it possible to accept (and later redirect) HTTP requests in a first step in order to keep the page "live" and let me test it?
- My site has very good SEO rankings (indexed as "http://www.example.com"), so properly redirecting is a must.
已采纳解答
原帖链接 · Tero Kilkanen · CC BY-SA 3.0
This configuration makes what you ask:
server {
listen 80;
listen [::]:80;
server_name www.example.com example.com;
# redirects both www and non-www to https
return 301 https://example.com$request_uri;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name www.example.com;
include snippets/ssl-example.com.conf;
include snippets/ssl-params.conf;
# redirects www to non-www
return 301 https://example.com$request_uri;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com;
include snippets/ssl-example.com.conf;
include snippets/ssl-params.conf;
charset utf-8;
# rest of my config
}
I changed rewrite to return, since that is a bit more efficient.
With return one has to use $request_uri to get the request path and arguments into the redirect URL.
Then I changed the server_name example.com; with listen 443; block to serve the actual contents of the site, and server_name www.example.com; with listen 443; to make redirect.
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
