Hash模式下Nginx部署前端项目
hash 模式下,仅 hash 符号之前的内容会被包含在请求中,如http://localhost:8080/#/login, 只有http://localhost:8080会被包含在请求中 ,因此对于服务端来说,即使没有配置location,也不会返回404错误
直接上代码server {
listen 80;
server_name 域名或ip地址;
location / {
root /绝对路径/dist;
# hash 模式下,仅 hash 符号之前的内容会被包含在请求中,如 website.com/#/login
# 只有 website.com 会被包含在请求中 ,因此对于服务端来说,即使没有配置location,也不会返回404错误
index index.html index.htm;
}
location ^~ /api {
add_header 'Access-Control-Allow-Origin' *;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PATCH, DELETE, PUT, OPTIONS';
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X_Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
# 去除传过来的 '/api'
rewrite "^/api/(.*)$" /$1 break;
}
}history模式下部署前端
vue history模式下路由是通过JS来执行视图切换的,当我们进入到子路由时刷新页面,web容器没有相对应的页面此时会出现404,所以我们只需要配置将任意页面都重定向到 index.html,把路由交由前端处理。
直接上代码server {
listen 443 ssl;
server_name 域名;
ssl_certificate 域名.pem;
ssl_certificate_key 域名.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
root /绝对路径/dist;
index index.html index.htm;
# vue history模式下路由是通过JS来执行视图切换的,当我们进入到子路由时刷新页面,web容器没有相对应的页面此时会出现404
#所以我们只需要配置将任意页面都重定向到 index.html,把路由交由前端处理
try_files $uri $uri/ /index.html;
}
location /api {
add_header 'Access-Control-Allow-Origin' *;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PATCH, DELETE, PUT, OPTIONS';
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X_Forwarded-For $proxy_add_x_forwarded_for;
# 去除 /api 前缀
rewrite "^/api/(.*)$" /$1 break;
proxy_pass http://127.0.0.1:8080;
}
}