nginx - 如果我的 nginx 配置错误,如何更正?

标签 nginx redirect configuration proxypass

我是 Nginx 新手。我尝试使用搜索 www 和 stackoverflow 来学习。大多数情况下,我会得到帮助来了解如何构建我的 nginx 配置。

我的域名为 www.mysite.com。一切; 目标网页错误服务器错误必须重定向到默认的index.html。我还定义了我的访问和错误日​​志。所有这些都在/etc/nginx/conf.d/default.conf 中完成(下面的代码)。

我需要重定向 (proxy_pass) /admin/user 以及与它们相关的任何内容。例如/admin 也有不同的文件夹,如/admin/login/。我需要/admin 之后的所有内容都必须重定向。/user 也是如此。

1) 看看我的代码,我是否正确重定向了 location/adminlocation/user

2) 我还使用 try_files $uri $uri/=404;在重定向中。它还会将 404 重定向到默认的 index.html。我做得对吗?

3) 我还拒绝访问某些文件和文件夹。我做得对吗?

我的主要问题是如果我的 nginx 配置错误,如何纠正?因此,为了理解正确的 nginx 配置,我将我的问题分为上面 3 个不同的问题。我希望我没有阻止 stackoverflow 如何提问指南。

谢谢。

更新:

server {
    charset UTF-8;
    listen 80;
    listen [::]:80;

    server_name www.mysite.com;
    access_log  /var/log/nginx/host.access.log  main;
    error_log  /var/log/nginx/host.error.log  main;

    # define a root location variable and assign a value
    set $rootLocation /usr/share/nginx/html;

    # define www.mysite.com landing page to the static index.html page
    location / {
        root   rootLocation;
        index  index.html index.htm;
    }

    # define error page to the static index.html page
    error_page 404  /index.html;
    location = /index.html {
        root rootLocation;
        internal;
    }

    # redirect server error pages to the static index.html page
    error_page   500 502 503 504  /index.html;
    location = /index.html {
        root   rootLocation;
        internal;
    }

    # redirect www.mysite.com/admin to localhost
    # /admin or /admin/ or /admin/**** must be redirect to localhost
    location /admin {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass "http://127.0.0.1:3000";
    }

    # redirect www.mysite.com/user to localhost
    # /user or /user/ or /user/**** must be redirect to localhost   
    location /user {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass "http://127.0.0.1:3001";
    }
}

最佳答案

通常将 root 语句放置在 server block 中一次,而不是在多个 location block 中重复相同的值。


您正在使用 proxy_pass 更改 URI,然后再将其传递到上游。在这种情况下,location 值和 proxy_pass 值的 URI 部分应该都以 / 结尾,或者都不以 /结尾。请参阅this document了解详情。

通常您不想希望将 try_filesproxy_pass 放置在同一位置。这会导致 Nginx 在允许请求传递到上游之前检查其文档根中是否存在该文件。


您不需要拒绝对配置文件的访问,因为这些文件一开始就不应该位于文档根目录内。

关于nginx - 如果我的 nginx 配置错误,如何更正?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56609102/

相关文章:

windows - 由于未知原因,无法在 Windows 上的 Docker 环境下运行 Nginx

django - 在 Redis 上设置 requirepass 会抛出 'NOAUTH Authentication required'

ruby-on-rails - Heroku 检测到 Rails 未设置为提供 static_assets

wordpress - 我网站的跳出率在一夜之间下降到几乎 0%,我想知道为什么?

node.js - MEVN Stack 启动后重定向至主页

url - Grails重定向到appName为空映射的URL

java - Autowired 属性为 null - Spring Boot 配置

vue.js - nginx - 将 facebook/bots 代理到不同的服务器而不更改规范 URL

c - nginx 内存池损坏?

java - 如何创建一个每次请求时都会重新读取的 hibernate 集合?