Как исправить ошибку 404 nginx на роутерах после установки letsencrypt

Я настраиваю новый сервер, работающий на vestaCP+NGINX+php-fpm и бэкенде laravel, после установки letsencrypt я сталкиваюсь с ошибкой 404 на всех моих маршрутизаторах, кроме главной страницы. laravel .env в порядке, и мой nginx conf выглядит следующим образом, кроме того, панель управления создала еще один файл nginx conf для ssl. Сайт без проблем работает по http протоколу.

server {
    listen      xx.xxx.xxx.xx:443;
    server_name example.com www.example.com;
    root        /home/admin/web/example.com/public_html;
    index       index.php index.html index.htm;
    access_log  /var/log/nginx/domains/example.com.log combined;
    access_log  /var/log/nginx/domains/example.com.bytes bytes;
    error_log   /var/log/nginx/domains/example.com.error.log error;


    ssl         on;
    ssl_certificate      /home/admin/conf/web/ssl.example.com.pem;
    ssl_certificate_key  /home/admin/conf/web/ssl.example.com.key;

    location / {
             try_files $uri $uri/ /index.php$is_args$args;
    location ~* ^.+\.(jpeg|jpg|png|gif|bmp|ico|svg|css|js)$ {
        expires     max;
    }
    location ~ [^/]\.php(/|$) {
        fastcgi_param SCRIPT_FILENAME    $document_root$fastcgi_script_name;
        if (!-f $document_root$fastcgi_script_name) {
        fastcgi_pass    127.0.0.1:9001;

        fastcgi_index   index.php;
        include         /etc/nginx/fastcgi_params;
    }
}

error_page  403 /error/404.html;
error_page  404 /error/404.html;
error_page  500 502 503 504 /error/50x.html;

location /error/ {
    alias   /home/admin/web/example.com/document_errors/;
}

location ~* "/\.(htaccess|htpasswd)$" {
    deny    all;
    return  404;
}
location /vstats/ {
    alias   /home/admin/web/example.com/stats/;
    include /home/admin/conf/web/example.com.auth*;
}

include     /etc/nginx/conf.d/phpmyadmin.inc*;
include     /etc/nginx/conf.d/phppgadmin.inc*;
include     /etc/nginx/conf.d/webmail.inc*;

include     /home/admin/conf/web/nginx.example.com.conf*;
}

person AliMahdavi    schedule 10.02.2019    source источник


Ответы (1)


Проблема

Я не специалист по Nginx, но мне кажется, что все директивы location должны быть внутри директивы server, а сейчас их нет. Также у вас есть вложенные директивы location, которые, я думаю, не нужны...

Начните с попытки исправить это с помощью этого:

server {
    listen      xx.xxx.xxx.xx:443;
    server_name example.com www.example.com;
    root        /home/admin/web/example.com/public_html;
    index       index.php index.html index.htm;
    access_log  /var/log/nginx/domains/example.com.log combined;
    access_log  /var/log/nginx/domains/example.com.bytes bytes;
    error_log   /var/log/nginx/domains/example.com.error.log error;


    ssl         on;
    ssl_certificate      /home/admin/conf/web/ssl.example.com.pem;
    ssl_certificate_key  /home/admin/conf/web/ssl.example.com.key;

    location / {
        try_files $uri $uri/ /index.php$is_args$args;
    }

    location ~* ^.+\.(jpeg|jpg|png|gif|bmp|ico|svg|css|js)$ {
        expires     max;
    }

    location ~ \.php$ {
        # https://nealpoole.com/blog/2011/04/setting-up-php-fastcgi-and-nginx-dont-trust-the-tutorials-check-your-configuration/
        #try_files $uri =404;
        #try index.php =404;

        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        #fastcgi_pass php:9000;
        fastcgi_pass  127.0.0.1:9001;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_intercept_errors off;
        fastcgi_buffer_size 16k;
        fastcgi_buffers 4 16k;
    }

    error_page  403 /error/404.html;
    error_page  404 /error/404.html;
    error_page  500 502 503 504 /error/50x.html;

    location /error/ {
        alias   /home/admin/web/example.com/document_errors/;
    }

    location ~* "/\.(htaccess|htpasswd)$" {
        deny    all;
        return  404;
    }

    location /vstats/ {
        alias   /home/admin/web/example.com/stats/;
        include /home/admin/conf/web/example.com.auth*;
    }

    include     /etc/nginx/conf.d/phpmyadmin.inc*;
    include     /etc/nginx/conf.d/phppgadmin.inc*;
    include     /etc/nginx/conf.d/webmail.inc*;

    include     /home/admin/conf/web/nginx.example.com.conf*;
}

ПРИМЕЧАНИЕ. Это не тестировалось, поэтому попробуйте его в разработке, и если вы исправите какой-либо синтаксис в файле или ошибку, сообщите мне, чтобы я мог обновить ответ. Если вы не можете исправить, сообщите нам, что пошло не так, чтобы мы могли попытаться помочь.

Возможное улучшение

После того, как вы используете Laravel, вы можете попытаться следовать конфигурации Nginx Php Docker Stack, который сразу работает с Laravel.

Бит, который вам нужно скопировать, чтобы заменить текущий в вашей директиве Nginx conf server{}, таков:


    # In Laravel we only need serve index.php
    location @proxyphp {
        rewrite (.*) /index.php;
    }

    # serving only index.php increases the security in your application. 
    location ~ /index\.php$ {
        # https://nealpoole.com/blog/2011/04/setting-up-php-fastcgi-and-nginx-dont-trust-the-tutorials-check-your-configuration/
        #try_files $uri =404;
        #try index.php =404;

        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass php:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_intercept_errors off;
        fastcgi_buffer_size 16k;
        fastcgi_buffers 4 16k;
    }

    # Deny access to all php files that are not index.php
    location ~ \.php$ {
        deny all;
    }

Улучшения безопасности

В Laravel нам нужно только обслуживать index.php, и это повышает безопасность вашего приложения, поскольку у него есть только 1 общедоступная точка входа, вместо того, чтобы быть доступным для любого *.php в папке public приложения Laravel.

person Exadra37    schedule 10.02.2019
comment
извините, но решение мне не помогло, я получил nginx: [emerg] host not found in upstream error - person AliMahdavi; 10.02.2019
comment
Вы заменили xxx.xxx:443 на свой IP и обновили example.com на свой собственный домен? Теперь я вижу, что забыл обновить fastcgi_pass в своем ответе, чтобы отразить тот, который вы использовали ... Я обновлю его. - person Exadra37; 10.02.2019
comment
конечно, я сделал все, но ничего не изменилось - person AliMahdavi; 10.02.2019
comment
Жаль это слышать... вы применили последние изменения, которые я сделал после моего последнего комментария. Я изменил с fastcgi_pass php:9000; на fastcgi_pass 127.0.0.1:9001;. - person Exadra37; 10.02.2019