前言
nginx是一款轻量级的http服务器,采用事件驱动的异步非阻塞处理方式框架,这让其具有极好的io性能。我们在日常开发中使用到nginx的主要有以下几个场景:
- nginx作为http服务器
- 跨域请求
- 负载均衡
- 网络资源的动静分离
作为前端,我们主要是关注前两个场景
一、下载安装
,下载完成后解压,解压后文件如下:
解压(双击nginx.exe,双击后一个黑色的弹窗一闪而过)
找到nginx解压目录下,鼠标右键,找到git bash打开,输入命令start ./nginx.exe回车即启动了nginx服务.
**检查是否启动成功:**直接在浏览器地址栏输入网址http://localhost,回车,出现以下页面说明启动成功
二、nginx配置
找到nginx下的conf/nginx.conf文件,设置代理相关信息,重点是server{}中的内容
#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_names_hash_bucket_size 128; server { listen 80; server_name localhost; location / { root html; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } server { listen 80; server_name test-local.juejin.com; # 这里是你要代理的测试环境域名加上-local # 比如你的项目测试环境为a.test.com,你本地此处可以设置为a-local.test.com,当然你可以随便设置 location /{ add_header 'access-control-allow-origin' '*'; add_header 'access-control-allow-credentials' 'true'; add_header 'access-control-allow-methods' 'get, post, options'; add_header 'access-control-allow-headers' 'dnt,web-token,app-token,authorization,accept,origin,keep-alive,user-agent,x-mx-reqtoken,x-data-type,x-auth-token,x-requested-with,if-modified-since,cache-control,content-type,range'; add_header 'access-control-expose-headers' 'content-length,content-range'; # 此处8091是我们本地运行项目的端口号,设置成跟你本地起的服务端口号一样就行 proxy_pass http://127.0.0.1:8091/; } } }
三、本机dns配置
**修改本地host文件配置,**找到目录c:\windows\system32\drivers\etc,打开hosts文件,修改文件,加入127.0.0.1 a-local.test.com
四、运行
先输入./nginx.exe -t检查nginx配置是否正确,正确如下图:
继续输入nginx -s reload重启(nginx配置文件修改后都要重启nginx才会生效)
刷新dns: ipconfig /flushdns
在浏览器中输入http://a-local.test.com, 你将会看到你本地运行的代码界面
五、常用的nginx命令
- 帮助命令:nginx -h
- 启动nginx服务器 :start nginx
- 配置文件路径:/usr/local/nginx/conf/nginx.conf
- 检查配置文件:nginx -t
- 停止服务:nginx -s stop
- 退出服务(处理完所有请求后再停止服务):nginx -s quit
- 重新加载配置文件:nginx -s reload
- 显示版本信息并退出 nginx -v
- 杀死所有nginx进程 killall nginx
六、跨域请求
前后端分离的项目中由于前后端项目分别部署到不同的服务器上,我们首先遇到的问题就是跨域,在这个场景我们下nginx可以帮助我们很好地解决这个问题
#跨域请求server server{ listen 9000; server_name 127.0.0.1; # 或者设置为本机ip root /app/crossdomain/; index index.html; location /douban/ { #添加访问目录为/api的代理配置 rewrite ^/api/(.*)$ /$1 break; proxy_pass http://a.test.com; } }
总结
到此这篇关于本地通过nginx配置反向代理的文章就介绍到这了,更多相关本地通过nginx配置反向代理内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!