Nginx

Nginx 和 Django 使用 www 前綴域

  • August 31, 2014

試圖了解如何強制 www。在我的域中並重定向任何類似 ww.example.com 或 test.example.com -> www.example.com

當我訪問 www.example.com 或 example.com 時,一切正常,如果人們嘗試訪問錯誤的域,我只是想掩飾自己,我不應該添加除“www.example.com”和“之外的任何內容” example.com’ 在我的 django ALLOWED_HOSTS

我根據以下設置一切:

如何使用 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;
   }
}

您尚未在 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;
   }
}

引用自:https://serverfault.com/questions/624855