nginx 配置解决前端跨域问题

一、为什么会出现跨域问题
       出于浏览器的同源策略限制。同源策略(Sameoriginpolicy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。同源策略会阻止一个域的。javascript脚本和另外一个域的内容进行交互。所谓同源(即指在同一个域)就是两个页面具有相同的协议(protocol),主机(host)和端口号(port。

二、什么是跨域
1.当一个请求url的协议、域名、端口三者之间任意一个与当前页面url不同即为跨域。

nginx 是静态页面的web服务器,服务器与服务器之间访问是不存在跨域的,所以通过nginx服务器去代理访问后端服务就不会跨域,跨域只在本地会出现,线上的地址访问不会出现跨域的。

nginx.conf 文件配置:

#user  nobody;

worker_processes  1;

#error_log  logs/error.log;

#error_log  logs/error.log  notice;

#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


 

events {

    worker_connections  1024;

}


 

http {

    include       mime.types;

    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '

    #                  '$status $body_bytes_sent "$http_referer" '

    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;

    #tcp_nopush     on;

    #keepalive_timeout  0;

    keepalive_timeout  65;

    #gzip  on;

    server {

        listen       80;

        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {

            #root   html;

             # 此处注意地址为指向你本地启动的前端项目的目录(即你的本地前端项目的所在地址,注意nginx用的是反斜杠/),如果是vue项目就是index.html的上一级目录(前端启动axios请求的baseURL = '',配置好后前端访问不要访问启动的项目地址,直接访问nginx代理地址:127.0.0.1,因为是本地启动的nginx,所以直接访问127,nginx默认端口是80),如果是静态的html项目,也是index.html的上一级目录.

#如果发布线上的项目配置的nginx这里就是存放的是vue打包后dist包的地址的上一层目录,也就是说vue前端包放在html目录的下面

            root   D:/abc/H5/html;

            index  index.html index.html;

        }

#下面就是配置的需要代理的后端接口的服务地址,表示所有以/custom/开头的接口请求服务代理到http://10.18.21.124:8888上,返回相应的数据

        location /custom/ {

        proxy_pass http://10.18.21.124:8888;

        }

        location /ram/ {

        proxy_pass http://10.18.21.124:8888;

        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html

        #

        error_page   500 502 503 504  /50x.html;

        location = /50x.html {

            root   html;

        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80

        #

        #location ~ \.php$ {

        #    proxy_pass   http://127.0.0.1;

        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000

        #

        #location ~ \.php$ {

        #    root           html;

        #    fastcgi_pass   127.0.0.1:9000;

        #    fastcgi_index  index.php;

        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;

        #    include        fastcgi_params;

        #}

        # deny access to .htaccess files, if Apache's document root

        # concurs with nginx's one

        #

        #location ~ /\.ht {

        #    deny  all;

        #}

    }


 

    # another virtual host using mix of IP-, name-, and port-based configuration

    #

    #server {

    #    listen       8000;

    #    listen       somename:8080;

    #    server_name  somename  alias  another.alias;

    #    location / {

    #        root   html;

    #        index  index.html index.htm;

    #    }

    #}


 

    # HTTPS server

    #

    #server {

    #    listen       443 ssl;

    #    server_name  localhost;

    #    ssl_certificate      cert.pem;

    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;

    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;

    #    ssl_prefer_server_ciphers  on;

    #    location / {

    #        root   html;

    #        index  index.html index.htm;

    #    }

    #}

}

前端启动axios请求的baseURL = '',配置好后前端访问不要访问启动的项目地址,直接访问nginx代理地址:127.0.0.1,因为是本地启动的nginx,nginx已经指向启动的前端项目,所以直接访问127.0.0.1,nginx默认端口是80

二 如果是vue项目可以直接在vue.config.js里面配置

例如:

const url = 'http://30.11.20.99:8888'  // 连接后端接口的服务地址

// const url = 'http://localhost:8080'

const CompressionWebpackPlugin = require('compression-webpack-plugin')

const productionGzipExtensions = ['js', 'css', 'less', 'html', 'png', 'svg', 'jpg', 'json', 'ico', 'txt']

const px2rem = require('postcss-px2rem')

const postcss = px2rem({

  remUnit: 10

})

module.exports = {

  // publicPath: process.env.VUE_APP_ENVIRONMENT === 'XG_prod' ? '/lggy' : '/',

  publicPath: '/',

  outputDir: 'dist',

  productionSourceMap: false,

  configureWebpack: {

    plugins: [

      new CompressionWebpackPlugin({

        asset: '[path].gz[query]',

        algorithm: 'gzip',

        test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),

        threshold: 10240,

        minRatio: 0.8

      })

    ]

  },

  css: {

    loaderOptions: {

      less: {

        modifyVars: {

          'primary-color': '#28439d'

          // 'link-color': '#1DA57A',

          // 'border-radius-base': '2px',

          // 'layout-header-background': '#1890ff',

          // 'menu-dark-submenu-bg': '#00508e'

        },

        javascriptEnabled: true,

        postcss: {

          plugins: [

            postcss

          ]

        }

      }

    }

  },

  devServer: {

    disableHostCheck: true,

    proxy: {

      '/auth': {

        target: url,

        changeOrigin: true

      },

      '/meta': {

        target: url,

        changeOrigin: true

      },

      '/report': {

        target: url,

        changeOrigin: true

      },

      '/ram': {

        target: url,

        changeOrigin: true

      },

      '/custom': {

        target: url,

        changeOrigin: true

      },

      '/os-public': {

        // target: 'http://10.18.36.130:8888',

        target: 'http://10.18.21.124:8888',

        changeOrigin: true

      },

      '/dw-api': {

        target: 'http://47.100.53.88:9090',

        changeOrigin: true

      }

    }

  },

  lintOnSave: true

}

猜你喜欢

转载自blog.csdn.net/wwf1225/article/details/129954369