我有一个域名 (example.com) 和一个子域名 (sub.example.com),它们都托管在同一台服务器上。我想代理请求,以便http://sub.example.com/api/将于http://example.com/api/(以及参数)这是我的来自 sub.example.com 的 nginx 代码:
location /api {
rewrite /api/(.*) /api/$1 break;
proxy_pass http://example.com/api;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_buffering off;
}
这对我来说不起作用。有效的是:
location ~* ^/api/(.*)$ {
rewrite ^/api/(.*)$ http://example.com/api/$1 last;
}
编辑:我忘了说我的服务器定义包含一些有关 Yii 框架和 php 文件解析的规则。以下是完整的服务器语句:
server {
listen 80;
server_name sub.example.com;
access_log /var/log/nginx/sub.example.com.access_log main;
error_log /var/log/nginx/sub.example.com.error_log info;
root /var/www/localhost/htdocs/sub.example.com;
index index.php index.html index.htm default.html default.htm;
# location ~* ^/api/(.*)$ {
# rewrite ^/api/(.*)$ http://example.com/api/$1 last;
# }
location /api {
rewrite /api/(.*) /api/$1 break;
proxy_pass http://example.com/api;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# proxy_set_header Host $http_host;
proxy_redirect off;
proxy_buffering off;
break;
}
location / {
if (-f $request_filename) {
#expires max;
break;
}
if (!-e $request_filename) {
rewrite ^/(.*)$ /index.php?/$1 last;
}
}
location /index.php {
include /etc/nginx/fastcgi.conf;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /path-to/index.php;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_pass 127.0.0.1:9000;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
include /etc/nginx/fastcgi.conf;
fastcgi_index index.php;
fastcgi_intercept_errors on; # for easier debug
}
}
答案1
您正在将初始请求Host
标头传递sub.example.com
给example.com
:
proxy_set_header Host $http_host;
代理请求时,它可能会落在sub.example.com
vhost 或默认 vhost 中,而不是example.com
vhost,这取决于您的设置。
删除此行。