Saturday, January 29, 2011

apache mod_rewrite

Hi,

I want mod_rewrite to do this:

http://server/* -> redirect to http://server/app/*
http://server/app/* should not be redirected

http://server.domain/* -> redirect to http://server/app/*
http://server.domain/app* -> redirect to http://server/app/*

It has to work with mod_jk!

Edit: this is the final solution

` force use of host 'server'
RewriteCond %{HTTP_HOST} !^server$
RewriteRule ^(.*)$ server$1 [R,NE,L]

` prepend /app to URL if missing
RewriteCond %{request_uri} !^/app.*?
RewriteRule ^(.+?)$ app/$1 [R,NE,L]

Thanks to you, fahadsadah and Insanity5902! I'm hesitant to flag either one of you as 'correct', as both have provided valuable input that made up the final solution.

  • Use the following config directives (you probably want to add them to your .htaccess file):

    RewriteEngine on
    RewriteCond %{request_uri} !^/prepended
    RewriteRule ^(.+?)$ prepended/$1
    
    : I tried combining the two approaches: RewriteCond %{HTTP_HOST} !^server$ RewriteRule ^(.*)$ http://server/$1 [R,L] RewriteCond %{request_uri}!^/app RewriteRule ^(.+?)$ app/$1 [R,L] That gives me: RewriteCond: bad argument line '%{request_uri}!^/app'
    fahadsadah : Try `RewriteCond %{request_uri}!^/prepended/.+?`
    : A space was missing, RewriteCond %{request_uri} !^/prepended/.+? seems to work.
    fahadsadah : Edited the answer to contain the correct directives.
    From fahadsadah
  • This should work better

    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^server$ [NC]
    RewriteRule ^(.*)$ http://server/$1
    
    RewriteRule ^$ /app
    

    This is off the top of my head, but what should be happening. Request comes in, if it isn't using server for the host name, then it will redirect to http://server keeping the rest of the URI field intact. Then it will reprocess the rules again, skip the first one (since RewriteCond is false) and then process the RewriteRule. Which is saying, if the URI is empty send it to /app. If the URI is anything other then empty, it will use what is already there.

    So on top of what you already have, it should also work as

    http://server/foo -> http://server/foo
    http://server.domain/foo -> http://server/foo
    

    Let me know how that works, In my head it seems to work fine :)

    : Ok I'll try, is mod_jk a problem?
    : "If the URI is anything other then empty, it will use what is already there." Can I rewrite the URL so that is /app is missing, it will prepend /app to the rest of the URL? Thanks so far!
    Insanity5902 : That is what the second rewrite rule does. The `^` tells it to look for the start of the URI and the `$` looks for the end. So since it is empty it will forward it to /app
    Insanity5902 : as for as mod_jk, I don't think it will be a problem , but not for certain as I've never used it.

0 comments:

Post a Comment