文章目录
- 问题
- 分析
- 解决
问题
在部署完项目后 刷新页面,页面进入了404
分析
- 加载单页应用后路由改变均由浏览器处理,而刷新时将会请求当前的链接,而Nginx无法找到对应的页面
关键代码try_files,剩下俩如果其他地方配置了则可以省略。
在这里解释一下try_files的意思,顾名思义try files 尝试获取文件。
如果一个地址是localhost:8899/login
那么uri指的是login地址,uri/指的是login文件夹
解决
添加一行代码:
location / {
root /www/wwwroot/phm/phmweb;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
这段代码的意思是,如果访问一个地址首先会尝试读取第一个地址的页面文件,第一个地址无法访问的话会访问同名文件夹,如果文件夹也不存在那么就返回默认的index.html文件,这样配置好之后再刷新就能正常显示了
附上我的 nginx.conf
文件
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
listen 9000;
server_name localhost;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# 路径映射
location /api {
proxy_pass http://39.106.6.253:82;
proxy_connect_timeout 600;
proxy_read_timeout 600;
rewrite "^/api/(.*)$" /$1 break;
}
location / {
root html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}