nginx宝塔面板如何配置跨域?

宝塔 Nginx 跨域问题Access-Control-Allow-Origin 的解决方案
1. 如果是使用nginx作为服务器的:
打开网站的设置,然后找到配置文件,添加如下代码:

nginx宝塔面板如何配置跨域?

  1. add_header 'Access-Control-Allow-Origin' '*';
  2. add_header 'Access-Control-Allow-Credentials' 'true';
  3. add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';

添加完之后,记得重启 nginx。

如果你需要指定特定域名的跨域请求时,可以在 Access-Control-Allow-Origin 中明确写出允许的域名。这样做可以增加安全性,避免不必要的跨域请求。以下是如何修改你的 Nginx 配置来实现这一点的例子:

  1. location / {
  2. # 只允许来自 指定https://域名.com 的跨域请求
  3. if ($http_origin ~* (http://2.baiu\.cc|https://ttmoban\.com)) {
  4. add_header Access-Control-Allow-Origin $http_origin;
  5. add_header Access-Control-Allow-Credentials 'true';
  6. }

  7. # 允许特定的请求方法
  8. add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';

  9. # 允许特定的请求头字段
  10. add_header Access-Control-Allow-Headers 'Authorization, Content-Type';

  11. # 处理预检请求
  12. if ($request_method = 'OPTIONS') {
  13. add_header 'Access-Control-Allow-Origin' $http_origin;
  14. add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
  15. add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type';
  16. add_header 'Access-Control-Allow-Credentials' 'true';
  17. add_header 'Content-Length' 0;
  18. add_header 'Content-Type' 'text/plain charset=UTF-8';
  19. return 204;
  20. }
  21. }

海螺主题

海螺主题

  • 注册时间 : 2023-09-02 15:19:36
  • 此页面仅展示用户的基本资料信息

回帖 ( 0 )