我有一个NodeJS应用程序运行在AWS EC2实例上托管的Ubuntu 16服务器上的端口3000上。我希望NGINX将以下每个地址重定向到http://example.com
:
http://www.example.com
https://example.com
/etc/nginx/sites-available/default
为此,我将server {
listen 80;
listen [::]:80;
server_name example.com;
location / {
# Redirect any http requests to https
return 301 https://www.$server_name$request_uri;
}
location ~* \.(?:ico|svg|woff|woff2|ttf|otf|css|js|gif|jpe?g|png)$ {
proxy_pass http://127.0.0.1:3000;
expires 30d;
add_header Pragma public;
add_header Cache-Control "public";
}
}
# Settings for a TLS enabled server
server {
listen 443 ssl http2;
listen [::]:443 ssl;
server_name www.example.com;
ssl_certificate "/etc/letsencrypt/live/example.com/fullchain.pem";
ssl_certificate_key "/etc/letsencrypt/live/example.com/privkey.pem";
# Automatically route HTTP to HTTPS
add_header Strict-Transport-Security "max-age=31536000";
include /etc/nginx/default.d/*.conf;
location / {
proxy_pass http://127.0.0.1:3000;
}
}
文件配置如下:
http://example.com
但是,这似乎只能部分起作用:
https://example.com
->转到 https://www.example.com
,而不是 http://www.example.com
https://example.com
->转到 https://www.example.com
,而不是 https://example.com
https://example.com
->转到 https://www.example.com
,而不是 https://www.example.com
有什么建议吗?
答案 0 :(得分:1)
对于每种要重定向的情况,您都应该有一个服务器块:
server {
listen 80;
listen [::]:80;
server_name example.com;
return 301 https://www.example.com$request_uri;
}
server {
listen 80;
listen [::]:80;
server_name www.example.com;
return 301 https://www.example.com$request_uri;
}
# Settings for a TLS enabled server
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com;
return 301 https://www.example.com$request_uri;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name www.example.com;
ssl_certificate "/etc/letsencrypt/live/example.com/fullchain.pem";
ssl_certificate_key "/etc/letsencrypt/live/example.com/privkey.pem";
# Automatically route HTTP to HTTPS
add_header Strict-Transport-Security "max-age=31536000";
include /etc/nginx/default.d/*.conf;
location / {
proxy_pass http://127.0.0.1:3000;
}
}