通过nginx实现线上页面访问本地接口

 现在很多web项目是前后端分离的,后端程序员想在本地通过页面测试接口时有些不方便,这时我们可以利用nginx,将静态请求直接转到线上,将接口请求转到本地。

 下载nginx windows版本,解压后在conf目录下新建自己的配置toutiao.conf

server {
        listen       8088;
        server_name  www.toutiao.im;

        location / {
            root   html;
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

    location ~ /wenda {
	allow 127.0.0.1;
	allow 10.0.0.0/8;
	
        deny all;

        keepalive_timeout  300s;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_pass   http://localhost:8083;
        add_header Access-Control-Allow-Origin '*';
	
	#access_log  /Users/shenhongxi/dev/nginx/logs/access.log combined;
    }

    location  = / {
        rewrite ^ /index.html;
    }


    location ~* \.(html|htm|js|css|png|jpg|gif|map)$ {
	allow 127.0.0.1;
	allow 10.0.0.0/8;

	deny all;

	proxy_pass   http://www.toutiao.im;
	#root /Users/shenhongxi/work/360/wenda/code/wenda-static/;
        autoindex off;
        add_header Access-Control-Allow-Origin '*';
    }
}

 在nginx.conf末尾添加 include toutiao.conf;

cmd启动nginx: start nginx 停止nginx.exe -s stop 重新加载nginx.exe -s reload

启动本地接口 127.0.0.1:8083

由于既要访问本地,又要访问线上,所以我们需要在浏览器级别设置hosts 127.0.0.1:8088

Host Switch Plus 这个chrome插件可以在浏览器级别切换hosts,配合nginx使用

https://chrome.google.com/webstore/search/Host%20Switch%20Plus?utm_source=chrome-ntp-icon

猜你喜欢

转载自wely.iteye.com/blog/2387070