window使用nginx代理本地文件
前言
之前写过一篇文章使用http-sever+fiddle 的组合,代理本地静态文件,将本地请求转发到线上服务器。现在用nginx尝试一下,记录一下使用过程中的问题及解决方式
一、nginx 安装
1.下载、解压
下载地址
*我下载的是nginx-1.20.1
指令文件是自己创建的,记录一些常用的指令
二、使用nginx代理本地文件
1.修改nginx配置
#user nobody;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
#gzip on;
server {
listen 80;
server_name localhost;
#配置跨域
add_header Access-Control-Allow-Orgin *;
add_header Access-Control-Allow-Headers X-Request-With;
add_header Access-Control-Allow-Method GET,POST,OPTIONS,PUT,DELETE;
location / {
root D:\\software\\JetBrains\\components\\nginx-1.20.1\\html;
autoindex on;
#index *.jpg;
}
}
}
这里把静态文件放在 nginx下的 html 目录下
注意
1.不要直接点 nginx.exe 启动,这样启动很不方便,要从 任务管理器中杀进程才行
2.一些简单常用的指令
start nginx : 启动nginx服务
nginx -s reload : 修改配置后重新加载生效
nginx -s reopen : 重新打开日志文件
nginx -s stop : 快速停止或关闭Nginx
nginx -s quit : 正常停止或关闭Nginx:
nginx -t -c {path}/nginx.conf : 测试nginx配置文件是否正确
tasklist /fi "imagename eq nginx.exe" : 检查是否正常启动
Linux
nginx : 直接启动nginx服务
nginx -s reload : 修改配置后重新加载生效
nginx -s reopen : 重新打开日志文件
nginx -s stop : 快速停止或关闭Nginx
2.增加反向代理地址
配置文件如下
#user nobody;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
#gzip on;
server {
listen 80;
server_name localhost;
#配置跨域
add_header Access-Control-Allow-Orgin *;
add_header Access-Control-Allow-Headers X-Request-With;
add_header Access-Control-Allow-Method GET,POST,OPTIONS,PUT,DELETE;
location / {
root html;
autoindex on;
#index *.jpg;
}
#反向代理
location ~ /{path1}/\S*\.(html|css|js)? {
proxy_pass http://host:port;
root html;
autoindex on;
}
location ~ /{path2}/\S*\.(html|css|js)? {
root html;
autoindex on;
}
location ~ /{path2}/\S*$ {
proxy_pass http://host:port;
}
# location / {
# root html;
# autoindex on;
# #index *.jpg;
# }
}
}
配置好,重新加载,访问就欧克了,对用的 path1 、path2、host、port改成你想代理的就行了
总结
使用这种方式来进行替换之前的fiddle的方式要方便很多,不得不感叹一下 nginx 牛B。而且作为技术人,在用已知的方案可以达到目的时,也可以尝试下别的方式,这是种成长。准备两套方案,有备无患
问题一.访问出现500 Internal Server Error
解决方式:location -》root 》路径中的 “\” 改为 “\\”