nginx一个端口部署多个地址,css、js等文件404

新手上路,请多包涵

具体需求就是在当前域名下的/doc/地址映射到其他vue项目

以下是nginx.conf配置文件

server {
    listen 80;#监听端口
    server_name localhost;#域名
    index index.html index.htm index.php;
    root nginx/html;#站点目录
    location / {
      root html/monitor;
      index index.html index.htm;
      try_files $uri $uri/ /index.html;
    }

    location /doc/ {
      proxy_pass localhost:81;
    }


    location ~* \.(gif|jpg|jpeg|png|css|js|ico|css|eot|svg|ttf|woff|mov)$ {
      root html/monitor;
      expires 48h;
      access_log off;
    }

    location ~ .*\.(php|php5)?$ {
      #fastcgi_pass unix:/tmp/php-cgi.sock;
      fastcgi_pass 127.0.0.1:9000;
      fastcgi_index index.php;
      # include fastcgi.conf;
    }

    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|ico)$ {
      expires 30d;
      # access_log off;
    }

    location ~ .*\.(js|css)?$ {
      expires 15d;
      # access_log off;
    }
}


  server {
    listen 81;#监听端口
    server_name localhost;#域名
    index index.html index.htm index.php;
    root nginx/html;#站点目录
    location / {
      root html/doc/doc;
      index index.html index.htm;
      try_files $uri $uri/ /index.html;
    }

    location ~* .*\.(gif|jpg|jpeg|png|css|js|ico|css|eot|svg|ttf|woff|mov)$ {
      root html/doc-public/doc;
      expires 48h;
      access_log off;
    }

    location ~ .*\.(php|php5)?$ {
      #fastcgi_pass unix:/tmp/php-cgi.sock;
      fastcgi_pass 127.0.0.1:9000;
      fastcgi_index index.php;
      # include fastcgi.conf;
    }

    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|ico)$ {
      expires 30d;
      # access_log off;
    }

    location ~ .*\.(js|css)?$ {
      expires 15d;
      # access_log off;
    }

    access_log off;
  }

遇到的问题:
然后映射的xxx.com/doc目录下,css和js文件加载不出来,请教一下各位大神如何解决。
image.png

已经尝试过location 的alias和root映射对应项目文件夹,也不行。
尝试过修改location ~ ^/doc/.*\.(js|css)?$*映射样式文件,也不行。

阅读 4.5k
2 个回答

问题可能出在这里

 location /doc/ {
  proxy_pass localhost:81;
}

因为后面有一段

location ~* \.(gif|jpg|jpeg|png|css|js|ico|css|eot|svg|ttf|woff|mov)$ {
  root html/monitor;
  expires 48h;
  access_log off;
}

这里匹配规则的 ~*/doc 优先级要高,所以当访问 /doc/ 目录下的静态文件的时候,它会被 ~* 下面的规则给提前匹配上。

改成

location ^~ /doc {
  proxy_pass http://localhost:81;
}

这样就会正常,因为 ^~ 的优先级会比 ~* 高,当静态资源请求以 /doc 路径开始时,会优先匹配 /doc , 匹配了 /doc 之后, /doc 路径下的资源文件请求能顺利转到 81端口下的那个服务。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题