2017-02-26 22 views
0

我有一個django單頁面應用程序。目前,當您訪問網站上不存在的網址時,會顯示404錯誤。但是,在這種情況下,我想重定向到該網站的主頁。我不確定我是否應該如何使用Nginx來做到這一點,或者有沒有辦法在Django中做到這一點?下面是我的Nginx文件。我嘗試使用下面的設置,但沒有奏效。如何使用Nginx將404請求重定向到Django單頁應用程序中的主頁?

error_page 404 = @foobar; 

location @foobar { 
    return 301 /webapps/mysite/app/templates/index.html; 
} 


upstream mysite_wsgi_server { 
    # fail_timeout=0 means we always retry an upstream even if it failed 
    # to return a good HTTP response (in case the Unicorn master nukes a 
    # single worker for timing out). 

    server unix:/webapps/mysite/run/gunicorn.sock fail_timeout=0; 
} 

server { 
    listen  80; 
    server_name kanjisama.com; 
    rewrite ^https://$server_name$request_uri? permanent; 
} 

server { 
    listen    443; 
    server_name   kanjisama.com; 
    ssl on; 
    ssl_certificate  /etc/letsencrypt/live/kanjisama.com/fullchain.pem; 
    ssl_certificate_key /etc/letsencrypt/live/kanjisama.com/privkey.pem; 
    ssl_protocols  TLSv1 TLSv1.1 TLSv1.2; 

    client_max_body_size 4G; 

    access_log /webapps/mysite/logs/nginx_access.log; 
    error_log /webapps/mysite/logs/nginx_error.log; 

    location /static/ { 
     alias /webapps/mysite/app/static/; 
    } 

    location /media/ { 
     alias /webapps/mysite/media/; 
    } 

    location/{ 
     if (-f /webapps/mysite/maintenance_on.html) { 
      return 503; 
     } 

     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
     proxy_set_header X-Forwarded-Proto https; 
     proxy_set_header Host $host; 
     proxy_redirect off; 

     # Try to serve static files from nginx, no point in making an 
     # *application* server like Unicorn/Rainbows! serve static files. 
     if (!-f $request_filename) { 
      proxy_pass http://mysite_wsgi_server; 
      break; 
     } 

    # Error pages 
    error_page 500 502 504 /500.html; 
    location = /500.html { 
     root /webapps/mysite/app/mysite/templates/; 
    } 

    error_page 503 /maintenance_on.html; 
    location = /maintenance_on.html { 
     root /webapps/mysite/; 
    } 

    error_page 404 = @foobar; 

    location @foobar { 
     return 301 /webapps/mysite/app/templates/index.html; 
    } 
} 

回答

1

首先,創建一個視圖來處理所有的404請求。

# views.py 

from django.shortcuts import redirect 

def view_404(request): 
    # make a redirect to homepage 
    # you can use the name of url or just the plain link 
    return redirect('/') # or redirect('name-of-index-url') 

其次,把你的項目的urls.py如下:

handler404 = 'myapp.views.view_404' 
# replace `myapp` with your app's name where the above view is located at 
相關問題