Nginx错误页面 - 适合所有人的一个位置规则?

Ali*_*xel 32 error-handling nginx http-status-code-404

拥有以下nginx vhost配置:

server {
    listen 80;
    listen 443 ssl;
    server_name default;
    root /var/www/default/html;
    error_log /var/www/default/log/error.log;
    access_log /var/www/default/log/access.log;
    ssl_certificate /etc/ssl/certs/ssl-cert-snakeoil.pem;
    ssl_certificate_key /etc/ssl/private/ssl-cert-snakeoil.key;

    autoindex on;
    index index.html index.php;

    location / {
        try_files $uri $uri/ @php;
    }

    location @php {
        rewrite ^/(.*)/?$ /index.php/$1 last;
    }

    location ~* /(?:[.]|.*[.](?:bak|fla|inc|ini|log|psd|sh|sql|swp)|(?:file|upload)s?/.*[.](?:php)) {
        deny all;
    }

    location ~* [.](?:php) {
        fastcgi_buffer_size             128k;
        fastcgi_buffers                 4 256k;
        fastcgi_busy_buffers_size       256k;
        fastcgi_connect_timeout         30;
        fastcgi_ignore_client_abort     off;
        fastcgi_index                   index.php;
        fastcgi_intercept_errors        on;
        fastcgi_pass                    unix:/var/run/php5-fpm.sock;
        fastcgi_read_timeout            60;
        fastcgi_send_timeout            60;
        fastcgi_split_path_info         ^(.+[.]php)(/.*)$;
        fastcgi_temp_file_write_size    256k;

        include /etc/nginx/fastcgi_params;
    }

    error_page 403 /403.html; location = /403.html {
        root /var/www/default/error;
    }

    error_page 404 /404.html; location = /404.html {
        root /var/www/default/error;
    }

    error_page 405 /405.html; location = /405.html {
        root /var/www/default/error;
    }

    error_page 500 501 502 503 504 /5xx.html; location = /5xx.html {
        root /var/www/default/error;
    }
}
Run Code Online (Sandbox Code Playgroud)

是否可以通过单个位置规则提供40x和50x错误?就像是:

error_page 403 /403.html;
error_page 404 /404.html;
error_page 405 /405.html;
error_page 500 501 502 503 504 /5xx.html;

location ~ /(?:40[345]|5xx)[.]html$ {
    root /var/www/default/error;
}
Run Code Online (Sandbox Code Playgroud)

如果我在上面,我总是得到nginx默认的404错误.字符串匹配(无运算符)和完全匹配(=运算符)工作,但使用case- [in]敏感正则表达式运算符(~[*])则不然.

我想问题是处理位置块的顺序.

无论如何要克服这一点来减少不必要的root冗余?

VBa*_*art 94

error_page 403 /error/403.html;
error_page 404 /error/404.html;
error_page 405 /error/405.html;
error_page 500 501 502 503 504 /error/5xx.html;

location ^~ /error/ {
    internal;
    root /var/www/default;
}
Run Code Online (Sandbox Code Playgroud)

  • 优秀的解决方 如果有人对此完全陌生,请注意您仍需要在/ var/www/default中创建"error"文件夹 (17认同)
  • ...或者使用`alias`而不是`root`,然后直接从`/ var/www/default /`读取文件,而不是`/ var/www/default/error /`. (8认同)
  • 我希望有一个服务器块可以响应任何服务器名称******(例如,IP地址将提供404页面).我希望该页面是自定义的.我写道:`listen 80 default_server; server_name默认值; 返回404; error_page 404 /errors/404.html; 位置^〜/ errors/{internal; root/var/www; }`.我仍然得到默认的nginx 404错误页面.`返回404;`使用自定义页面? (2认同)
  • 提示:如果您的错误页面使用的是静态文件,例如来自同一目录的images / css / ...,请省略“ internal;”。 (2认同)