问题描述: Vue使用history模式时,刷新非首页路由返回404
解决方案:
location / {
try_files $uri $uri/ /index.html;
}
问题描述: JS/CSS/图片等静态资源无法加载
解决方案:
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires max;
log_not_found off;
try_files $uri =404;
}
问题描述: Vue前端无法正确代理API请求到Laravel后端
解决方案:
location /api {
try_files $uri $uri/ /index.php?$query_string;
# Laravel特定配置
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
问题描述: 前端请求API时出现跨域错误
解决方案: 在Laravel中添加中间件或在Nginx中配置:
location /api {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization, X-Requested-With';
if ($request_method = 'OPTIONS') {
return 204;
}
}
问题描述: HTTPS站点加载HTTP资源导致警告
解决方案:
server {
listen 443 ssl;
# SSL配置...
# 强制所有请求使用HTTPS
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# 重定向HTTP到HTTPS
if ($scheme != "https") {
return 301 https://$host$request_uri;
}
}
问题描述: .env文件配置未生效
解决方案: 确保Nginx配置中设置了正确的根目录:
root /path/to/your/laravel/public;
index index.php index.html index.htm;
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
问题描述: 文件上传被Nginx限制
解决方案:
client_max_body_size 100M; # 设置上传文件大小限制
server {
listen 80;
listen [::]:80;
server_name yourdomain.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name yourdomain.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
root /var/www/your-project/public;
index index.php index.html index.htm;
# Laravel前端控制器
location / {
try_files $uri $uri/ /index.html;
}
# Laravel后端API
location /api {
try_files $uri $uri/ /index.php?$query_string;
}
# 静态文件缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires max;
log_not_found off;
}
# PHP处理
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
# 安全头
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
# 禁用.htaccess和其他隐藏文件
location ~ /\.(?!well-known).* {
deny all;
}
}
tail -f /var/log/nginx/error.log
journalctl -u php8.1-fpm -f
nginx -t
systemctl reload nginx
通过以上配置和解决方案,应该能够解决大多数Laravel与Vue在Nginx环境下的常见问题。