How do I force redirect all 404's (or every page, whether invalid or not) to the homepage?

后端 未结 6 1431
孤街浪徒
孤街浪徒 2020-12-07 19:06

Currently every invalid page is 500 (Internal Server Error) because I probably messed up with my server block configuration.

I decided to shut down my website a whil

6条回答
  •  一生所求
    2020-12-07 19:28

    This solution for nginx hosted site:

    Edit your virtual hosting file

    sudo nano /etc/nginx/sites-available/vishnuku.com 
    

    Add this snippet in the server block

    # define error page
    error_page 404 = @notfound;
    
    # error page location redirect 301
    location @notfound {
        return 301 /;
    }
    

    In your php block put the fastcgi_intercept_errors set to on

    location ~ \.php$ {
        include /etc/nginx/fastcgi_params;
        # intercept errors for 404 redirect
        fastcgi_intercept_errors on;
        fastcgi_pass unix:/run/php/php7.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
    

    Final code will look like this

    server {
        listen 80;
        server_name vishnuku.com;
    
        root /var/www/nginx/vishnuku.com;
        index index.php index.html;
    
        access_log /var/log/nginx/vishnuku.com.log;
        error_log /var/log/nginx/vishnuku.com.error.log;
    
        location / {
            try_files $uri $uri/ /index.php?$args /;
        }
    
        # define error page
        error_page 404 = @notfound;
    
        # error page location redirect 301
        location @notfound {
            return 301 /;
        }
    
        location ~ \.php$ {
            include /etc/nginx/fastcgi_params;
            fastcgi_intercept_errors on;
            fastcgi_pass unix:/run/php/php7.2-fpm.sock;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        }
    
        location ~ /\.ht {
            deny all;
        }
    
        location = /nginx.conf {
            deny all;
        }
    }
    

提交回复
热议问题