问题:部署vue项目时,访问后端域名时出现跨域问题,目前只能在nginx配置允许单个域名进行访问,想要通过其他方式实现域名可访问。
1.通过nginx配置语法add_header,在被访问的域名对应的nginx配置文件中添加以下配置
注:当前配置只允许指定单个域名访问
server {
# 允许指定域名跨域
add_header Access-Control-Allow-Origin https://xxx.xxx.com always;
add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;
add_header Access-Control-Allow-Headers *;
add_header Access-Control-Allow-Credentials true;
}
2.在nginx的add_header语法基础上,再与if、set语法结合,可实现多个域名进行跨域访问
a) 设置被访问域名nginx配置文件
server {
# 设置跨域访问域名
set $cors_origin "http://vue.xxx.com,http://vuebak.xxx.com";
# 判断:匹配则对访问域名进行重置
if ($http_origin ~* "^http://vue.xxx.com$") {
set $cors_origin $http_origin;
}
if ($http_origin ~* "^http://vuebak.xxx.com$") {
set $cors_origin $http_origin;
}
# 允许指定域名跨域
add_header Access-Control-Allow-Origin $cors_origin; # 允许跨域访问
add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;
add_header Access-Control-Allow-Headers *;
add_header Access-Control-Allow-Credentials true;
}
b) 请求域名nginx配置文件(vue.xxx.com、vuebak.xxx.com可以进行跨域访问;vuedump.xxx.com不可跨域访问)
server{
listen 80;
server_name vue.xxx.com;
index index.php index.html;
root /www/vue/dist/;
location / {
try_files $uri $uri/ /index.html?$query_string;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
location ~ /\.(?!well-known).* {
deny all;
}
access_log /nginx/logs/access-vue.xxx.com.log main;
error_log /nginx/logs/error-vue.xxx.com.log;
}
server{
listen 80;
server_name vuebak.xxx.com;
index index.php index.html;
root /www/vuebak/dist/;
location / {
try_files $uri $uri/ /index.html?$query_string;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
location ~ /\.(?!well-known).* {
deny all;
}
access_log /nginx/logs/access-vuebak.xxx.com.log main;
error_log /nginx/logs/error-vuebak.xxx.com.log;
}
server{
listen 80;
server_name vuedump.xxx.com;
index index.php index.html;
root /www/vuedump/dist/;
location / {
try_files $uri $uri/ /index.html?$query_string;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
location ~ /\.(?!well-known).* {
deny all;
}
access_log /nginx/logs/access-vuedump.xxx.com.log main;
error_log /nginx/logs/error-vuedump.xxx.com.log;
}
3.项目配置CORS
参考:https://blog.csdn.net/qq_36436407/article/details/108442230