由于生产环境限制,只能对外开放一个端口9988
,其他人写的项目也要用这个端口,所以只能用不同的请求路径来区分不同的项目。
我的项目是前后分离的。页面打包的内容放到服务器目录是:/usr/local/m2m/nbMsg/browser/dist
,java后台的端口是:8989
,且后台接口统一前缀/api/v1
。
我想配置成访问http://[host]:9988/nbmsg
,能够默认返回/usr/local/m2m/nbMsg/browser/dist
目录下的html静态页面文件,然后页面上的ajax请求都是/api/v1
开头的,需要代理到8989端口
。
下面是我的配置。一个server是原来已有的9988
端口的虚拟主机,另一个8999
端口的虚拟主机是我加上去的。我应该如何修改配置?让http://[host]:9988/nbmsg
的请求都转发到8999
端口的虚拟主机上?
server {
listen 9988;
root /server/html;
# Add index.php to the list if you are using PHP
index index.html index.htm index.php index.nginx-debian.html;
location / {
index index.html index.htm index.php;
# try_files $uri $uri/ =404;
}
location /business/ {
# root /server/html;
try_files $uri $uri/ /business/public/index.php?$query_string;
}
####################################################################
# request entrance
####################################################################
location /nbmsg {
proxy_pass http://127.0.0.1:8999;
proxy_set_header Host $http_host;
proxy_set_header X-Real_IP $remote_addr;
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /server/html;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept";
add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
}
}
####################################################################
# my virtural host
####################################################################
server{
listen 8999;
index index.html;
location / {
alias /usr/local/m2m/nbMsg/browser/dist;
}
location /api/v1 {
proxy_pass http://127.0.0.1:8989;
proxy_pass_header Server;
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
proxy_set_header Host $http_host;
proxy_set_header X-Real_IP $remote_addr;
client_max_body_size 300m;
client_body_buffer_size 256k;
proxy_buffer_size 128k;
proxy_buffers 8 32k;
proxy_busy_buffers_size 128k;
proxy_temp_file_write_size 128k;
}
}
"由于生产环境限制,只能对外开放一个端口9988,其他人写的项目也要用这个端口,所以只能用不同的请求路径来区分不同的项目。" 也就是说你们通过路径(location)来区分的应用,并不是域名(server_name)因此不存在后续的所谓“虚拟主机”的概念。而且nginx并不存在一个虚拟主机的概念(吐槽:部分博客、技术文章里面概念乱入),参见:Server Block Examples
从你的上下文分析,你的需求:
顺便说下,你这段含糊不清
很容易让人理解为你的ajax完成的url是
http://[host]:9988/api/v1
,但从你的配置中看又不是, 同时如果你使用了html base标签等,但代码中使用/api/v1类似相对路径的话又受base标签影响,也就是/api/v1这个路径的实际url仅从配置分析得出的是http://[host]:9988/nbmsg/api/v1
基于以上分析,调整后的配置如下: