Aug 13, 2011
tom

Apache rewrite rules behind a nginx proxy

Question

I am running nginx (:80) in front of an Apache webserver (:8080)

Nginx config (snippet):

location / {
    proxy_pass        http://www.domain.tld:8080;
    proxy_set_header  X-Real-IP  $remote_addr;

If I set localhost instead of www.domain.tld, my browser gets redirected to http://localhost:8080.

Apache rewrite rules:

RewriteEngine On
Options +FollowSymlinks
RewriteBase /RewriteCond %{HTTP_HOST} !^www.
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !..+$
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) http://%{HTTP_HOST}/$1/ [L,R=301]RewriteCond %{REQUEST_URI} !v2/
RewriteRule ^(.*)$ v1/$1 [L]

So far, so good.

However, every link (which uses relative paths) appears as http://www.domain.tld:8080/page instead of staying on port 80.

Is there any way to solve this through the rewrite rules? I don’t want to use absolute paths.

Thanks

Answer

Solved by adding this to the nginx config:

proxy_set_header Host $host; 
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

Related posts:

  1. Apache rewrite multiple conditions
  2. Rewrite Conditions Backreferences passed to all rules?
  3. Why do some rewrite rules fail while AJP is serving all of my requests to Tomcat?
  4. dynamic rewrites using $1, %1, %2 etc
  5. apache mod-rewrite to nginx rewrite

Leave a comment