Keep nginx from pushing backend port on try and redirects
Ever found yourself wondering why your nginx setup is returning a port from the backend vhost?
QUICK FIX: port_in_redirect off;
I found some tweaks to prevent this from happening, first a example:
# This is the result of a: try $uri $uri/ in a backend vhost
stein@stein ~ $ curl --head http://www.example.nl/test
HTTP/1.1 301 Moved Permanently
Server: nginx
Content-Type: text/html
Content-Length: 178
Connection: keep-alive
Location: http://www.example.nl:8080/test/
Accept-Ranges: bytes
X-Varnish: 1044342160
Age: 0
Via: 1.1 varnish
Vary: User-Agent
X-Cache: MISS
The nginx config I used before ifound out what was wrong is:
server {
listen 80;
server_name *.example.nl example.nl;
root /var/www/vhosts/example.nl/httpdocs;
include includes/default_vhost.conf; # proxy timeouts etc. nothing interesting
location / {
include includes/proxy_varnish.conf; # location with varnish related conf
} # varnish sends requests on to 8080 if not in cache
}
server {
listen 8080;
server_name *.example.nl example.nl;
root /var/www/vhosts/example.nl/httpdocs;
index index.php index.html index.htm;
location / {
index index.php;
try_files $uri $uri/ @handler;
}
location ~ .php/ {
rewrite ^(.*.php)/ $1 last;
}
location @handler {
rewrite / /index.php;
}
location ~ \.php/ {
rewrite ^(.*\.php)/ $1 last;
}
include includes/hhvm.conf; # Sends fascgi to hhvm
}
It frustrated me that the solution is not that well documented but here it is: port_in_redirect off;
Yes, noting exiting here, just place port_in_redirect off;
in the backend vhost. There is also a way to not send the full hostname: server_name_in_redirect off;
This will result in a config like this:
server {
listen 80;
server_name *.example.nl example.nl;
root /var/www/vhosts/example.nl/httpdocs;
include includes/default_vhost.conf; # proxy timeouts etc. nothing interesting
location / {
include includes/proxy_varnish.conf; # location with varnish related conf
} # varnish sends requests on to 8080 if not in cache
}
server {
listen 8080;
server_name *.example.nl example.nl;
root /var/www/vhosts/example.nl/httpdocs;
index index.php index.html index.htm;
port_in_redirect off;
location / {
index index.php;
try_files $uri $uri/ @handler;
}
location ~ .php/ {
rewrite ^(.*.php)/ $1 last;
}
location @handler {
rewrite / /index.php;
}
location ~ \.php/ {
rewrite ^(.*\.php)/ $1 last;
}
include includes/hhvm.conf; # Sends fascgi to hhvm
}