Let Nginx redirect non-www to www and redirect http 80 to https 443¶
Suppose that you're the maintainer of www.example.com and the site is served by Nginx, you may redirect the followig sites to https://www.example.com (url with www subdomain and https schema):
- http://www.example.com (http + www)
- http://example.com (http + non-www)
- https://example.com (https + non-www)
Nginx configuration Example¶
server {
listen 80;
server_name _;
return 301 https://www.example.com$request_uri;
}
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /path/to/crt;
ssl_certificate_key /path/to/key;
return 301 https://www.example.com$request_uri;
}
server {
listen 443 ssl;
server_name www.example.com;
ssl_certificate /path/to/crt;
ssl_certificate_key /path/to/key;
location / {
proxy_pass http://127.0.0.1:8080;
}
}
Notice:
- The first
serverdirective redirect all http request. - The second
serverdirective redirect non-www request.- DO NOT omit ssl related configurations.
- The third
serverdirective gives the detailed configuration of this site likelocationdirectives.
This article is originally created by tooli.top. Please indicate the source when reprinting : https://www.tooli.top/posts/nginx_www
Posted on 2022-05-01
Mail to author