Apache server allows you to redirect and rewrite URLs in many ways. But it does not preserve POST request data while redirecting URLs, by default. Sometimes you may need to retain POST data when you redirect URLs. In this article, we will look at how to redirect POST request data in .htaccess.
How to Redirect POST Request Data in .htaccess
Here are the steps to redirect POST request data using .htaccess.
1. Enable mod_rewrite
If you have already enabled mod_rewrite in Apache then you can skip this step. Otherwise, run the following commands to enable mod_rewrite, depending on your Linux system.
Ubuntu/Debian
Open terminal and run the following command to enable mod_rewrite
$ sudo a2enmod rewrite
Redhat/CentOS/Fedora
Open Apache configuration file in a text editor.
$ sudo vi /etc/apache2/httpd.conf
Look for the following line.
#LoadModule rewrite_module modules/mod_rewrite.so
Uncomment it by removing # at its beginning. If you don’t find this line, add it afresh.
Also look for the following Directory tag and change AllowOverride from None to All.
. . .
<Directory /var/www/html>
. . .
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride All
. . .
</Directory>
. . .
Also read : How to Exclude URL from Auth in Apache
2. Redirect Request POST data
Open/Create .htaccess file in a text editor.
$ sudo vi /var/www/html/.htaccess
Let us say you want to redirect POST request to www.example.com/file.php to www.example.com/sample.php along with its POST data, then simply add the following line in your .htaccess file.
RewriteEngine on
RewriteRule ^/file.php$ /sample.php [L,R=301,NC,P]
In the above RewriteRule, we use the following flags & characters,
^ – matches beginning of URL
$ – matches end of URL
L – stop processing after this rule
R=301 – permanent redirect
NC – case sensitive rule
P – get content via proxy
In the above rule, the P flag ensures that your POST data is preserved during redirection.
If the above RewriteRule does not work for you, try the following
RewriteEngine on
RewriteRule ^/file.php$ /sample.php [L,R=307]
In the above rule, we use the following,
^ – matches beginning of URL
$ – matches end of URL
L – stop processing after this rule
R=307 – request must be repeated with same HTTP method and data
In the above rule, R=307 ensures that POST request data is preserved during redirection.
Also read : How to Exclude Folder from Rewrite Rule in .htaccess
3. Restart Apache Server
Restart Apache Server to apply changes.
$ sudo service apache2 restart
That’s it. Now all POST requests directed to /file.php will be redirected to /sample.php along with its POST data.
Also read : How to Check Concurrent Connections in Apache Server
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.