外观
有时候服务端不自带web容器,然后接口又没有做跨域支持,前端并不想在服务器上多部署一个服务,那么如果服务器上使用了nginx的话,可以直接通过配置nginx达到请求转发的目的。
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
root /usr/share/nginx/html;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / {
}
location /hcm {
proxy_pass http://127.0.0.1:8081;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Read-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}需要注意的是这里的配置:
location /hcm {
proxy_pass http://127.0.0.1:8081;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Read-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}这里的location /hcm配上后面的proxy_pass http://127.0.0.1:8081;会将所有指向/hcm路径下的请求都转发到服务器上8081端口对应的服务上,请求路径本身不会发生变化,即/hcm/test.do的请求会被转发到8081服务的/hcm/test.do接口上。 如果这里把location /hcm换成location /hcm/,则转发后的请求路径只会保留/hcm之后的部分,即/hcm/test.do的请求会被转发到8081服务的/test.do接口上。