Nginx 和 Django 使用 www 前缀的域名

Nginx 和 Django 使用 www 前缀的域名

尝试了解如何强制在我的域中使用 www. 并重定向任何内容,例如 ww.example.com 或 test.example.com -> www.example.com

当我访问 www.example.com 或 example.com 时,一切都正常,我只是试图在人们尝试访问错误的域名时保护自己,并且我不应该在我的 django ALLOWED_HOSTS 中添加除“www.example.com”和“example.com”之外的任何内容

我按照以下设置了一切:

如何使用Django一键安装镜像

upstream app_server {
    server 127.0.0.1:9000 fail_timeout=0;
}

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /usr/share/nginx/html;
    index index.html index.htm;

    client_max_body_size 4G;
    server_name _;

    keepalive_timeout 5;

    # Your Django project's media files - amend as required
    location /media  {
        alias /home/django/django_project/django_project/media;
    }

    # your Django project's static files - amend as required
    location /static {
        alias /home/django/django_project/django_project/static; 
    }

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://app_server;
    }
}

答案1

您尚未在 nginx 中定义任何重定向指令。这里是正确的配置。

#here the redirect section. If server doesn't match www.example.com or example.com, it will redirected to http://www.example.com
server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    server_name _;

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

#your main config files, handles request whenever Host header match www.example.com or example.com
server {
    listen 80;
    listen [::]:80;

    root /usr/share/nginx/html;
    index index.html index.htm;

    client_max_body_size 4G;
    server_name www.example.com;

    keepalive_timeout 5;

    # Your Django project's media files - amend as required
    location /media  {
        alias /home/django/django_project/django_project/media;
    }

    # your Django project's static files - amend as required
    location /static {
        alias /home/django/django_project/django_project/static; 
    }

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://app_server;
    }
}

相关内容