近期在ubuntu上部署前端项目接触了nginx的代理,然后想到之前前端项目都是用的webpack(http-proxy-middleware)来代理处理跨域问题。那么是不是直接用nginx也行呢。带着疑问进行了测试:
一、首先进行nginx的安装
本文以windows上为例,安装nginx安装包,然后到目录中conf/nginx.conf中进行配置。
二、nginx配置
server {
listen 80;
#server_name localhost;
server_name test.com; #域名访问。本地进行测试的时候需要修改host文件映射到127.0.0.1
location / {
root html;
index index.html index.htm;
proxy_pass http://127.0.0.1:3000; #浏览器访问80端口的时候,会代理到本地启动的项目
};
location /api/ {
#假设请求地址为http://localhost/api/,将会代理到https://www.test.com/api/,这样就可以解决请求的跨域问题
proxy_pass https://www.test.com/api/;
}
三、nginx命令
因为直接打开nginx.exe文件,会重复打开多个nginx进程,所以此处用命令来启动,首先进入到nginx安装目录下
开启: start nginx
停止:.\nginx -s stop
重启:.\nginx -s reload