walterhpdx
walterhpdx

Reputation: 21

Apache redirect of multiple PHP pages based on variable

I have a current site that I'm keeping up though it's deprecated and all content moved to another site. Because it's been a year, I want to start redirecting people from the old site to the new, and I can do that grossly with a simple redirect. However, I've got individual articles that I'd like to redirect to the article on the new site.

The old schema was something like:

https://mydomain/viewstory.php?sid=20449

That was imported to the new site as:

https://mynewdomain/works/12345

The data is in my MySQL database with old and new URL, and I'd like to put together a giant .htaccess file with all the redirects. But currently the code I have input does NOT work. That code I'm using is:

Redirect 301 /viewstory.php?sid=20449 https://mynewdomain/works/12345

Is there any way to do this?

Upvotes: 1

Views: 139

Answers (1)

MrWhite
MrWhite

Reputation: 45948

Redirect 301 /viewstory.php?sid=20449 https://mynewdomain/works/12345

The mod_alias Redirect directive matches against the URL-path only, not the query string. To match this URL you would need to use mod_rewrite and check the QUERY_STRING server variable in a condition. For example:

RewriteEngine On

RewriteCond %{QUERY_STRING} ^sid=20449$
RewriteRule ^viewstory\.php$ https://mynewdomain/works/12345 [QSD,R=301,L]

The QSD flag is necessary to discard the original query string from the redirect response.

I'd like to put together a giant .htaccess file with all the redirects.

This may be OK if this is all you are using the old host for... redirecting to the new site on a different server/virtualhost. Although, how many individual redirects do you have?

However, ordinarily, if you are maintaining old and new sites on the same server/virtualhost then it is more efficient to implement 100s (or 1000s) of redirects in your application, rather than .htaccess (or even the server config). And only when your application has deemed the request would result in a 404. This is to ensure that normal site visitors are not impacted in any way by the redirect logic (.htaccess is processed on every single request).

Alternatively, you internally rewrite (in ./htaccess) all requests of the form /viewstory.php?sid=<something> to a separate script and that script handles the redirects.

For example:

RewriteEngine On

# Rewrite all requests of the form "/viewstory.php?sid=<something>" to a PHP script
RewriteCond %{QUERY_STRING} ^sid=.
RewriteRule ^viewstory\.php$ manage-old-redirects.php [L]

In the above we internally rewrite (no redirect) all requests of the form /viewstory.php?sid=<something> to your PHP script /manage-old-redirects.php, in which you perform the necessary lookups to construct the redirect as required.

Upvotes: 3

Related Questions