Search code examples
apachemod-rewriteurl-rewritingmod-proxy

Apache RewriteRule flags proxy NS


I'm trying to write the following rules (see comments)

# Redirect example.org/sub/* to sub.example.org/* explicitly
RewriteCond %{REQUEST_URI} ^/sub(.+)$ [NC]
RewriteRule ^ http://sub.%{HTTP_HOST}%1 [L,R=301,NS]

# Redirect sub.example.org/* to example.org/sub/* internally
RewriteCond %{HTTP_HOST} ^sub\.(.+)$ [NC]
RewriteRule ^ http://%1/sub%{REQUEST_URI} [L,P,NS]

Even with NS flag, when I hit sub.example.org/foo I get too many redirects, here is RewriteLog

applying pattern '^' to uri 'foo'
rewrite 'foo' -> 'http://example.org/sub/foo'
escaped URI in per-dir context for proxy, http://example.org/sub/foo -> http://example.org/sub/foo
forcing proxy-throughput with http://example.org/sub/foo
go-ahead with proxy request proxy:http://example.org/sub/foo [OK]

applying pattern '^' to uri 'sub/foo'
rewrite 'sub/foo' -> 'http://sub.example.org/foo'
explicitly forcing redirect with http://sub.example.org/foo
escaping http://sub.example.org/foo for redirect
redirect to http://sub.example.org/foo [REDIRECT/301]

On and on


Solution

  • # Redirect example.org/sub/* to sub.example.org/* explicitly
    RewriteCond %{REQUEST_URI} ^/sub(.+)$ [NC]
    RewriteRule ^ http://sub.%{HTTP_HOST}%1 [L,R=301]
    
    # Redirect sub.example.org/* to example.org/sub/* internally
    RewriteCond %{HTTP_HOST} ^sub\.(.+)$ [NC]
    RewriteRule - http://%1/sub%{REQUEST_URI} [L,P]
    

    No NS flag, just dash... doh