背景
最近使用Nginx部署Vue项目时,发现页面不是根路由(/
)的情况下会出现404的情况,网上搜寻了一下解决方法,原来是由于Vue单页面开发特性导致的,这里记录一下解决方法。
方案
只需要在Nginx配置中添加以下内容即可:
location / {
try_files $uri $uri/ @router;
index index.html index.htm;
}
location @router {
rewrite ^.*$ /index.html last;
}
在1panel的配置
server {
listen 80 ;
listen 443 ssl http2 ;
server_name ***;
index index.php index.html index.htm default.php default.htm default.html;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header X-Real-IP $remote_addr;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $http_connection;
access_log /www/sites/***/log/access.log main;
error_log /www/sites/***/log/error.log;
location ^~ /.well-known/acme-challenge {
allow all;
root /usr/share/nginx/html;
}
location / {
try_files $uri $uri/ @router;
index index.html index.htm;
}
location @router {
rewrite ^.*$ /index.html last;
}
root /www/sites/***/index;
error_page 404 /404.html;
include /www/sites/***/proxy/*.conf;
if ($scheme = http) {
return 301 https://$host$request_uri;
}
...省略ssl配置
}