Docker nginx 配置单页面应用

我有一个单页面应用用Angular开发的,router采用的是history模式,我在本地想测试部署到nginx是否可以成功访问时遇到404问题,网上找了些资料说是需要设置try_files $uri $uri/ @router; 可是我试了还是不行,求大家帮忙看下,谢谢。

deploy nginx的脚本:

set -e;
docker rm -f my-nginx;
docker run --name my-nginx -d -p 80:80 \
-v /Desktop/my-nginx/conf/nginx.conf:/etc/nginx/nginx.conf \
-v /Desktop/my-nginx/log:/var/log/nginx \
-v /Desktop/my-nginx/html:/usr/share/nginx/html \
nginx

nginx的conf文件:

user  nginx;
worker_processes  1;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    server {
        listen      80;

        location ^~ /test {
            try_files $uri $uri/ /test/index.html; 
        }
       
    }
    
    keepalive_timeout  65;
    include /etc/nginx/conf.d/*.conf;
}
我的应用文件全部放在test目录下,当访问`http://localhost/test`时正常,如果访问`http://localhost/test/myUrl` 就报404

2020/06/23 08:06:40 [error] 28#28: *10 open() "/usr/share/nginx/html/test/myUrl" failed (2: No such file or directory), client: 172.17.0.1, server: localhost, request: "GET /test/myUrl HTTP/1.1", host: "localhost"

阅读 3.3k
2 个回答

SPA 整这么复杂干啥?

照着改:

server {
    listen 80;
    location / {
        root /usr/share/nginx/html/test; # 这个是你入口文件所在的目录,如果不对就改
        index index.html index.htm;
        try_files $uri $uri/ /index.html =404; # index.html 是你的入口文件,如果不叫这个名,改
    }
    
    # 把你原来那第二个 location 删掉
}

先论证一下用history的必要性
如果没必要,就放弃history,所有问题就解决了
有几个用户会关心地址栏里的“#”
真想搞你系统的人,也不会因为没有“#”就没办法的
千万别自己骗自己

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