Nginx 部署 Vue 单页面应用及 PHP 接口,解决跨域问题
写过前后端分离项目的童鞋都知道, Vue 项目打包后会生成一个 dist 文件夹,需要将这个文件夹放在服务器上,配置一个域名去访问。
PHP、JAVA、GO 等后台语言写的接口一般也需要配置一个域名去访问,此时用户从 Vue 的单页面网页中访问接口域名就会出现跨域的各种问题。例如,浏览器在处理复杂请求时会先自动使用 Option
请求进行嗅探,我个人是非常不喜欢这个 Option
嗅探的,假设一个接口的响应时间为 20 ms,若多发送一次 Option
请求,服务器就会增加一份压力,同时也会增加 20ms 的请求时间。
其次是浏览器在跨域访问时, Cookie、Header 等经常会出现一些问题,所以为了避免这些问题发生,干脆直接把单页应用域名与接口域名使用同一个域名,不同的前缀去访问接口,这样就不会出现跨域问题。
所以本文针对目前PHP主流框架 Laravel5.6 以及 ThinkPHP5.1 写了2个伪静态的配置, 这样妈妈再也不用担心我们跨域啦, 嘻嘻
dist文件夹即单页应用的目录, 而public文件夹即 ThinkPHP 或 Laravel 的入口文件夹。
访问 admin.lcgod.com/* 则会匹配单页应用 /www/dist
里的应用
访问 admin.lcgod.com/api 则优先匹配 PHP 接口 /www/api
里的应用
完整 nginx.conf 配置如下:
Laravel5.6
server {
listen 80;
server_name admin.lcgod.com;
root /www/dist;
index index.html;
location /api {
try_files $uri $uri/ /index.php?$query_string;
}
location / {
try_files $uri $uri/ /index.html;
}
location ~ \.php(.*)$ {
root /www/api/public;
index index.php;
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
ThinkPHP5.1
server {
listen 80;
server_name admin.lcgod.com;
root /www/dist;
index index.html;
location /api {
if (!-e $request_filename) {
rewrite ^/api/(.*)$ /index.php?s=/$1 last;
}
}
location / {
try_files $uri $uri/ /index.html;
}
location ~ \.php(.*)$ {
root /www/api/public;
index index.php;
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
配置完 nginx.conf,不要忘了重启 nginx 进程:
service nginx reload
发布评论
评论
共计
1条评论
最新评论