通过url参数在nginx上基于区域设置设置自定义404错误页

通过url参数在nginx上基于区域设置设置自定义404错误页,nginx,webserver,nginx-location,Nginx,Webserver,Nginx Location,我在GNU/Linux操作系统上运行最新稳定版本的Nginx,并拥有以下虚拟主机,我试图设置自定义本地化404错误页面,避免if,但我总是以重定向循环结束 到目前为止,我只考虑以下区域设置es,en和ca,它们是我作为URL参数得到的,总是在域旁边。预期的URL类似于: http://www.example.com/ca http://www.example.com/ca/home http://www.example.com/en http://www.example.com/en/conta

我在
GNU/Linux
操作系统上运行最新稳定版本的
Nginx
,并拥有以下虚拟主机,我试图
设置自定义本地化404错误页面,避免if
,但我总是以重定向循环结束

到目前为止,我只考虑以下区域设置
es
en
ca
,它们是我作为URL参数得到的,总是在域旁边。
预期的URL类似于:

http://www.example.com/ca
http://www.example.com/ca/home
http://www.example.com/en
http://www.example.com/en/contact
这是我的nginx服务器块:

server {
        listen          80;
        listen          [::]:80;
        server_name     example.com;
        root            /var/www/html/example_com;
        # By default, show Castilian index
        index           es/index.html;

        access_log      /var/log/nginx/example_com.access.log main;
        error_log       /var/log/nginx/example_com.error.log error;

        #Remove HTML Extension
        rewrite ^(/.*)\.html(\?.*)?$ $1$2 permanent;

        # Remove trailing slash
        rewrite ^/(.*)/$ /$1 permanent;

        # Make sure Nginx knows what files to look for, and for that we use the try_files directive.
        # Look for a file with the current $uri and an .html extension, and if no file exists, 
        # check for a directory with that name and serve the index. Otherwise, render a 404 error.
        try_files $uri/index.html $uri.html $uri/ $uri =404;

        location = /form/contact.php {
                deny all;
                return 404;
        }

        # Custom error pages
        set $error404 /en/404.html;

        location /ca {
            set $error404 /ca/404.html;
        }

        error_page 404 =404 $error404;


        location = /form/contact {
                try_files $uri.php =404;

                include /etc/nginx/fastcgi_params;
                fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
                send_timeout 1800;
                fastcgi_read_timeout 1800;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
        }

        location ~ /\.ht {
            deny  all;
        }

        location ~ /(config) {
                deny all;
                return 404;
        }
    }

您不能像那样使用位置块,您将打断所有其他位置块。有关详细信息,请参阅

有一个更简单的方法。使用命名位置来处理404响应,只需将原始URI重写到所需的错误页面中

例如:

error_page 404 @error404;

location @error404 {
    rewrite ^/(en|es|ca) /$1/404.html last;
    rewrite ^ /en/404.html last;
}

有关更多信息,请参阅。

只需在服务器内部的配置文件中添加以下错误页面重定向行

error_page 404 https://www.example.com/404-page.html;

这就解决了我的问题

非常感谢您的帮助并提供了有效的解决方案。我也注意到了这些链接,我已经读了很多,但第一次很难找到一个有效的解决方案:)我编写了一个PHP脚本,可以从以下URL[1][2][3][4]访问,所以我在我的nginx配置文件中添加了以下位置块。到目前为止,它还可以正常工作,只是错误地允许类似以下语言环境重复的URL[5][6]。你能帮我把它修好吗?我正在把我找到的位置块贴在这里。[1] [2][3][4][5][6]这是我使用https goo.gl/rd221f的位置块。你应该开始一个新问题。