【问题标题】:Nginx redirects static files to subdir of rootNginx 将静态文件重定向到 root 的子目录
【发布时间】:2015-12-01 13:45:37
【问题描述】:

我有一个在http://192.168.0.2:8080/ 运行的应用程序。 index.html 页面位于/web 文件夹中,它在/css 处请求静态文件(例如css)。

我想使用nginx 作为反向代理并让myapp.mydomain.com 重定向到我的应用程序。 我的nginx.conf 中有以下配置:

server {
        listen       80;
        server_name  myapp.mydomain.com;
        satisfy any;
        location / {
                proxy_pass  http://192.168.0.2:8080/web/;
                index  index.html index.htm;
        }
}

但它不适用于css 文件,因为它会在/web/css 上查找它们。 我的解决方法是以这种方式配置我的nginx.conf(不带/web):

server {
            listen       80;
            server_name  myapp.mydomain.com;
            satisfy any;
            location / {
                    proxy_pass  http://192.168.0.2:8080/;
                    index  index.html index.htm;
            }
    }

并且每次都请求http://myapp.mydomain.com/web

但我希望能够请求http://myapp.mydomain.com/ 并让nginx 管理。

我认为类似的东西可能会有所帮助,但我找不到方法:

location ~ .(css|img|js)/(.+)$ {
                try_files $uri /$uri /$1/$2;
        }

location / {
                proxy_pass  http://192.168.0.2:8080/web/;
                index  index.html index.htm;
        }

这是我的完整文件,包括身份验证等:

upstream app { server 192.168.0.2:8080; }
server {
        listen       80;
        server_name  myapp.mydomain.com myapp.myOtherDomain.com;
        satisfy any;
        allow 192.168.0.0/24;
        deny all;
        auth_basic "closed site";
        auth_basic_user_file /etc/nginx/auth/passwords;
        location / { proxy_pass http://app/web/; }
        location /css { proxy_pass http://app; }
        location /img { proxy_pass http://app; }
        location /js { proxy_pass http://app; }
}

知道如何解决这个问题吗?

谢谢。

【问题讨论】:

  • 请扩展您的问题以包括整个server { ... } 容器。请给出一个被映射到 /web/css 的 CSS 资源的示例 URL。
  • 我编辑了这个问题。我希望现在更清楚了。
  • 也许你只需要location = / { rewrite ^ /web/; }
  • 我应该把那个放在哪里?我无法理解,抱歉。

标签: javascript css image nginx static


【解决方案1】:

据我了解,您有一个工作配置,唯一问题是您希望将 URL http://myapp.mydomain.com/ 映射到 http://192.168.0.2:8080/web/

您的工作配置是:

server {
  listen       80;
  server_name  myapp.mydomain.com;
  satisfy any;
  location / {
    proxy_pass  http://192.168.0.2:8080/;
    index  index.html index.htm;
  }
}

最简单的解决方案是为/ URI 添加完全匹配。如:

server {
  listen       80;
  server_name  myapp.mydomain.com;
  satisfy any;
  location = / { rewrite ^ /web/; }
  location / {
    proxy_pass  http://192.168.0.2:8080/;
    index  index.html index.htm;
  }
}

【讨论】:

  • 是的,它有效。非常感谢。很锋利。当我想重写所有的静态文件时,你重写了 web。再次非常感谢您。
猜你喜欢
  • 2011-06-14
  • 2015-12-14
  • 1970-01-01
  • 1970-01-01
  • 2017-02-06
  • 2018-10-30
  • 1970-01-01
  • 2012-09-30
  • 1970-01-01
相关资源
最近更新 更多