我已经看到了多种方法来处理将http://example.com或example.com(带有或不带有www。)或https://example.com重定向到https://www.example.com的处理。
我的使用方式是在此nginx配置中:
error_log /dev/stdout info;
upstream django_server {
server app:8001 fail_timeout=0;
}
server {
listen 80;
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/nginx/ssl/certificate.chained.crt;
ssl_certificate_key /etc/nginx/ssl/example.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
return 301 https://www.example.com$request_uri;
}
server {
listen 80;
server_name www.example.com;
add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
return 301 https://www.example.com$request_uri;
}
server {
listen 443 default_server ssl;
server_name www.example.com;
client_max_body_size 4G;
charset utf-8;
keepalive_timeout 70;
add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
gzip on;
gzip_http_version 1.1;
gzip_disable "MSIE [1-6]\.";
gzip_min_length 256;
gzip_vary on;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain text/css text/javascript application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss;
gzip_comp_level 9;
ssl_certificate /etc/nginx/ssl/certificate.chained.crt;
ssl_certificate_key /etc/nginx/ssl/example.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
location /static/ {
root /usr/share/nginx/sasite/;
expires 30d;
autoindex off;
location /static/download/ {
location ~* \.(pdf|docx|zip|rar)$ {
add_header Content-Disposition 'attachment; filename="$request_filename"';
}
}
}
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_redirect off;
if (!-f $request_filename) {
proxy_pass http://django_server;
break;
}
}
}
但是我也看到了这样的版本,其中设置了多个server_name
值,如下所示:
server {
listen 80;
server_name example.com www.example.com;
add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
return 301 https://www.example.com$request_uri;
}
server {
listen 443 default_server ssl;
server_name example.com www.example.com;
client_max_body_size 4G;
charset utf-8;
keepalive_timeout 70;
add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
ssl_certificate /etc/nginx/ssl/certificate.chained.crt;
ssl_certificate_key /etc/nginx/ssl/example.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
}
我也看到了其他方法来执行此操作,但这似乎并不有效。处理这种情况的实际理想方法是什么?我目前的配置有效,但是我想学习最佳实践。
答案 0 :(得分:1)
这取决于偏好。您是否希望用户始终看到(或始终看不到)“ www”。一部分?如果是这样,请使用重定向方法。如果您不在乎他们是否看到,请使用多个server_name / server_alias条目。