Learn about .htaccess 301 Redirect for URLs with a query string

Occasionally, you may need to redirect a URL that includes a query string. This will require that you use the RewriteEngine in order to have the redirect rule properly bring your viewers to the correct page. Follow the directions in the tutorial below to create a redirect rewrite rule for a specific page. The redirect will work with a query string.

How to Identify a URL using a query string

You will need to first identify those instances where you need to use this type of rewrite rule. It’s very easy to identify URLs with a query string. You will see a question mark after the page reference and then a value will be expressed. For example:

https://sample-site.com/querypage.php?id=5

The query string occurs after the question mark. These values are the result of the query that may generate a particular page. In this example, you will need to rewrite the URL so that the new domain is used while keeping the query values. The code presented below is the 301 re-write for needed redirect using the query string. In this we’re simply rewriting the domain to “new_domain.com” while adding the value of the query string to the end of the URL.

RewriteEngine On 
RewriteCond %{REQUEST_URI}  ^\/querypage\.php$ 
RewriteCond %{QUERY_STRING} ^id=([0-9]*) 
RewriteRule ^(.*)$ https://new_domain.com/querypage/%1 [R=301,L]

What is this code? The “RewriteCond %[REQUEST_URI}”, “RewriteCond %{QUERY_STRING}” and “RewriteRule” are the Apache server commands. These commands require the mod_rewrite to be active. After each command is a regular expression used to identify or match part of the URL. For more information see the offical Apache documentation for Apache Module mod_rewrite (version 2.4).

Breakdown of the rewrite code for understanding:

RewriteEngine On – This enables the mod_rewrite engine module.

RewriteCond %{REQUEST_URI} This identifies the URL request submitted in the browser. The regular expression identifies the unique portion of the URL request with the expression ^/querypage.php$. The ^ (carat) indicates the start and the $ indicates the end of the portion of the URL being identified. The “\” is used in front of any periods within the URL. Note that this condition is case sensitive. To make it case insensitive you would add the flag [NC] at the end of the statement.

RewriteCond %{QUERY_STRING} identifies the query string within the URL. In this case, it is “id=5”. The regular expression is used to identify the value starts the statement with a carat symbol (^), then ends it with a “$”.

The final part of the redirect for your URL with a query string is the actual rewrite rule. This is the section that changes the URL as long as the rewrite conditions are met.

RewriteRule ^(.*)$ https://new_domain.com/querypage/%1 [R=301,L]

The beginning of the rewrite rule – ^(.*)$ – identifies what you’re changing, which is the total URL. The second part – https://new_domain.com/querypage%1 – shows what is being rewritten. Note that the “%1” portion identifies the value matched in the query string ({QUERY_STRING}) condition.

The final part of the rule – [R=301,L] – indicates the type of redirect being used “R=301” and the flag “L” which basically means that this is the end of the rule. The rewrite will stop processing at this point.

Now that you understand the different parts of the actual rewrite code let’s review the process of writing the Rewrite for a query string.

How to write the 301 Redirect for a page with a query string URL

  1. RewriteEngine-on Your rewrite code should start with RewriteEngine On. This assumes that the mod_rewrite module for your Apache server is active. NOTE: The mod_rewrite module is active on InMotion Hosting servers by default.
  2. request URI Determine the URL being requested that triggers the rewrite. For example, this condition can be a specific and unique page within the URL that you wish to redirect. In the example used in this tutorial – RewriteCond %{REQUEST_URI} ^/querypage\.php$ – the requested URI is specified to “querypage.php”.
  3. query string The next line of the rewrite is the portion that identifies the value used in the query string – RewriteCond %{QUERY_STRING} ^id=([0-9]*). This query matches any numeric value provided for the ID. It is later referenced in the rewrite rule with “%1”.
  4. Finally, the fourth line in the code is the rewrite rule. The rewrite is not executed unless the previous listed conditions are met. In this case, here’s the rewrite rule:RewriteRule ^(.*)$ https://new_domain.com/querypage/%1 [R=301,L]The re-written URL will look like the following:https://new_domain.com/querypage/5

    Once the URL has been rewritten, it will be sent to the browser and displayed in place of the old URL and the user will be redirected to that new location. As per the last part of the rule, this is a 301 redirect and it is then flagged to terminate at that point.

This should provide you with enough information to create your own 301 redirect for pages using a query string. There are many ways to make redirects and also many ways to write the regular expression portion of the redirect. If you are not familiar with using regular expression, then our recommendation is to consult with an experienced developer. Make sure that you make a backup of your site before making any changes to your website files.

AC
Arnel Custodio Content Writer I

As a writer for InMotion Hosting, Arnel has always aimed to share helpful information and provide knowledge that will help solve problems and aid in achieving goals. He's also been active with WordPress local community groups and events since 2004.

More Articles by Arnel

10 thoughts on “Learn about .htaccess 301 Redirect for URLs with a query string

  1. Wondering if it’s possible to rewrite TWO conditions. I want to change the URL format AND add the query string! So for example, http://59.mysite,com?key=12345 becomes http://www.mysite.com/cgi-bin/script.pl?user=59&key=12345. (If the code can pass it directly to the script, so much the better, but image I would have to get the .htaccess to reload the complete page)

  2. Hi,
    I want my server to read this page “https://my-domain.com/myapp.php?p=11” against the URL “https://my-domain.com/myapp/my-technical-effort”
    I have tried this htaccess rule
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_URI} ^/myapp\.php$
    RewriteCond %{QUERY_STRING} ^p=11
    RewriteRule ^(.*)$ https://mydomain.com/myapp/my-technical-effort [QSD,R=301,L]

    it redirect to new URL but server says page not found on this server with 404 error.
    Can you please help me to rewrite the rule so server can serve the page “https://my-domain.com/myapp.php?p=11” against the URL “https://my-domain.com/myapp/my-technical-effort”

    My current htaccess is as follows

    Header always append X-Frame-Options ALLOWALL

    RewriteEngine On
    RewriteCond %{HTTPS} !=on
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
    Header always set Content-Security-Policy “upgrade-insecure-requests;”

    Anyone can help me please?

    1. Hello! It looks like your question was posted twice, so I’m replying to your issue here. I discussed the issue with one of our senior support technicians, and they suggested that RewriteBase should probably be /myapp/ instead of just /. They emphasized that that was just a suggestion, though. You’ll need to check with your specific site configuration. That said, they also advised that if you are doing this for a WordPress site, it’s better to do this through WordPress itself, or a plugin, rather than manually editing the .htaccess file. I hope that helps!

  3. Hi! I’ve read your article that was very helpful but i’m still confused:

    I’ve to redirect this query: /showthread.php?exemple

    To this page: /exemple/

    I’ve tried with the code below but it does’t redirect:

    # Redirect Query String

    RewriteCond %{QUERY_STRING} /showthread.php?exemple
    RewriteRule (.*) /exemple/ [R=301,L]

    Hope you can help!

    Thanks

    1. Is “RewriteEngine on” above the redirect code? Also, the HTTP header info for the URL you’re trying to redirect could offer clues. You can use “curl –head URL” or https://viewdns.info/httpheaders/.

  4. We use Comodo cWatch for our security and the hack was cleaned long ago. The only problem that I’m still having is the hackers trying to access their links, which no longer exists, which is causing me 404 errors. I am fine with editing .htaccess files, but need some assistance, as stated above. Please help me to determine where in my .htaccess file I should put the redirect (in the WordPress section or outside of it) and what text to use to redirect from a file that has ever-changing query strings to go to my home page.

    1. All your redirect code should be maintained inside the same mod_rewrite tag (used for the standard WordPress permalink structure).

      We are unable to provide the text to use. If you are not familiar with using regular expression, I recommend you consult with an experienced developer for a custom coded solution.

      If you would like to learn more about the syntax required for what you are attempting to accomplish, I recommend that you review the Apache mod_rewrite module documentation, specifically the Rewrite Query section. That section should assist you with the query string changing. I hope this helps!

      Sincerely,
      Carlos D

  5. I had a hacker who added a directory with a file in it and then they went to that file name with a query string appended to the end of it to execute whatever malicious code they were doing. I have since removed that directory and file, yet they keep attempting to access it, causing me a ton of 404 errors in my Google Developer tools. I would like to redirect all of their queries to my website’s home page in my .htaccess file to get rid of the 404 errors in Google’s tools. 

    My site is a WordPress site – first of all, do I add my lines of code inside the WordPress code:

    <IfModule mod_rewrite.c>

    RewriteEngine On

    RewriteBase /

    RewriteRule ^index\.php$ – [L]

    RewriteCond %{REQUEST_FILENAME} !-f

    RewriteCond %{REQUEST_FILENAME} !-d

    RewriteRule . /index.php [L]

    </IfModule>

     

    Or do I create a new <IfModule mod_rewrite.c> for my redirect? If so, do I need to specify RewriteEngine On again? Or because it was already specified once in this file, it doesn’t need to be listed again?

    Secondly, this is the start of the file that I need to redirect:

    https://mywebsite.com/journal/75fug.php?pfdt=text-that-changes-with-each-instance

    And I want to send it to: https://mywebsite.com

    So I basically want to do away with all of the query string and the folder and php file name and redirect it all to my home page. I’ve only found tutorials that show how to keep the query string, but simply reformat it into a new file structure. How can I remove it completely? If you could help me figure out the code to insert, it would be greatly appreciated.

    1. Hello,

      Sorry to hear about your hacked site. The query would typically be in a file such as your .htaccess file. I would recommend reviewing our hacked site aritcles. It will help you make sure that things are cleared and secure. Also, you do have 3rd party options such as Sucuri. If they are accessing and writing to your .htaccess file, then adding code to it would not necessarily be your best option. Please review our articles and let us know if you have any further questions.

Was this article helpful? Join the conversation!