Jumpa
Jumpa

Reputation: 4409

Rewrite rule preserving post data

I'm trying to build a rewrite rule. I cannot redirect because I need to preserve POST and GET data. In particular, if not present I need to add the string "v1". So:

http://www.example.com/ -> http://www.example.com/v1

I tried:

RewriteEngine On
RewriteRule "/(.*)$" "/v1/$1" [NC,L]

But this is not working. Can you help me please?

EDIT: with the first answer:

RewriteRule !^/?v1/ /v1%{REQUEST_URI} [NC,L]

http://www.example.com -> OK
http://www.example.com/v1 -> not preserving POST data (GET OK)
http://www.example.com/v1/ -> OK, please why (I just added a slash after v1, but this is not the solution I'm looking for)?

Upvotes: 1

Views: 2205

Answers (1)

anubhava
anubhava

Reputation: 785196

Have it this way:

RewriteEngine On

RewriteRule !^/?v1/ /v1%{REQUEST_URI} [NC,L]

EDIT: Since /v1/ is a directory and you're entering http://www.example.com/v1 Apache's mod_dir module adds a trailing / to make it http://www.example.com/v1/ using a 301 redirect. POST data gets lost due to 301 redirect.

To prevent this behavior use this snippet:

DirectorySlash Off
RewriteEngine On

# add a trailing slash to directories silently
RewriteCond %{DOCUMENT_ROOT}/$1 -d
RewriteRule ^(.*?[^/])$ %{REQUEST_URI}/ [L]

RewriteRule !^/?v1(/.*)?$ /v1%{REQUEST_URI} [NC,L]

Upvotes: 2

Related Questions