Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

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"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 删掉
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...