重定向到单独的URL(如果是403或404)

时间:2019-11-20 06:33:33

标签: nginx nginx-reverse-proxy nginx-config

我有一个Nginx设置,其中包括一个包含白名单IP的文件,该文件可以访问我的站点的管理门户admin.site.com。如果未经授权的IP尝试访问我的管理门户,通常会根据配置返回403禁止或404,但是我觉得这不是很好。 如果响应是403或404,我需要将所有用户重定向到site.com。这就是我的

server {
    # listen on port 80 (http)
    listen 80;
    server_name admin.site.com;

    location ~ /.well-known/acme-challenge {
        allow all;
        root /var/www/.well-known/acme-challenge/;
        default_type "text/plain";
        try_files $uri =404;
    }

    location / {
        # redirect any requests to the same URL but on https
        return 301 https://$host$request_uri;
    }
}

server {
    # listen on port 443 (https)
    listen 443 http2 ssl;
    server_name admin.site.com;

    root /var/www/admin.site.com/site-frontend/;
    index index.html;
        location / {
       include /etc/nginx/snippets/whitelist.conf;
       try_files $uri $uri/ /index.html;
    }

    # location of SSL certificate
    ssl_certificate /etc/some/path/admin.site.com/fullchain.pem;
    ssl_certificate_key /etc/some/path/admin.site.com/privkey.pem;
    ...
    ...
    ... 

    # write access and error logs to /var/log
    access_log /var/log/nginx/admin.site.com_access.log;
    error_log /var/log/nginx/admin.site.com_error.log;
}

这是负责检查IP是否在白名单中的位:

    index index.html;
        location / {
       include /etc/nginx/snippets/whitelist.conf;
       try_files $uri $uri/ /index.html;
    }

如果返回403,如何重定向到site.com

1 个答案:

答案 0 :(得分:0)

您可以使用error_page伪指令将403和/或404状态页面重定向到外部站点。有关详细信息,请参见this document

例如:

error_page 404 403 =301 https://example.com/;