mtmehdi
mtmehdi

Reputation: 61

.htaccess, preserve post data on url rewrite

There are posts for similar issues everywhere but none worked in my case. I want to preserve the POST data when I rewrite the URL.

In my .htaccess file, I have

RewriteRule ^blogs/([a-z0-9]+)$ blog-details.php?blog=$1 [L]

When the form on this page is submitted, I get an empty array. How can I preserve the POST data with this url rewrite rule. Thanks in advance for your suggestions.

[EDIT] It might be due to the case that php extension is removed from the url. I have these rules at the beginning of my .htaccess file after RewriteEngine On.

RewriteCond %{THE_REQUEST} /([^.]+)\.php [NC]
RewriteRule ^ /%1 [NC,L,R]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [NC,L]

The complete .htaccess file is as below:

RewriteEngine on

RewriteCond %{THE_REQUEST} /([^.]+)\.php [NC]
RewriteRule ^ /%1 [NC,L,R]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [NC,L]

RewriteRule ^blogs/([a-z0-9-]+)$ blog-details.php?blog=$1 [L]

I have same issue when I rewrite other urls of such kind as well. Can someone please suggest a solution in this case. Thanks in advance for your suggestions and comments.

Upvotes: 1

Views: 1003

Answers (1)

MrWhite
MrWhite

Reputation: 45829

As noted in comments, internal rewrites do not lose POST data. (They do not change the request type.)

It may be due to the reason that php extension is removed from the url. I have these rules at the top of my .htaccess file.

Yes, possibly. If you are submitting to a URL with the .php extension then the 302 redirect will cause the browser to issue a GET request following the redirect response and the POST data will be lost. However, the form should be submitted to the canonical URL (ie. without the file extension), so the redirection to remove .php should have nothing to do with it.

If you are unable to modify the URL the form is submitted to then you can include an exception in the rule that removes the file extension (although this does somewhat defeat the point of having extensionless URLs to begin with).

You could add a condition so that only GET requests are redirected. For example:

RewriteCond %{REQUEST_METHOD} =GET [NC]
RewriteCond %{THE_REQUEST} \s/([^.?]+)\.php\s [NC]
RewriteRule ^ /%1 [L,R]

This should really be a 301 (permanent) redirect. (It currently defaults to a 302, temporary, redirect.)

Alternatively you change this to a 308 (permanent) redirect that should preserve the request method across the redirect. However, there is no point (and inefficient) redirecting the form submission.

To clarify, you are linking to URLs without the .php extension throughout your site?

Upvotes: 2

Related Questions