301 redirect with PHP and MySQL on 404

2019-07-31 08:34发布

问题:

I am transferring a large static website of 500+ pages to a Joomla installation but what I am wanting to do, rather than code a 500+ line .htaccess file, is to use PHP's built in 301 header redirect to dynamically redirect requests that come in to the new URL.

So for example, after I move the site, the following URL would 404 without a redirect-

http://www.foo.com/old_page.html

I would want it to redirect to

http://www.foo.com/old-page.php

So I would like to create a MySQL database of old URLs and their corresponding new URL and then, if the server is going to return a 404, for it first to check the DB for the existing old URL, and if matched, to issue a 301 redirect to the new URL. Right, am I making sense here?

How would I do that? I can "talk" the logic but not really sure where to begin or how to accomplish it because, while I understand PHP, I don't really understand how this would work with Apache (or even if it would for example...)?

And if you know of any scripts out there that are already doing this, all the better.

回答1:

In your Apache configuration, set an ErrorDocument of whatever /404handler.php script you like. In its run context, $_SERVER['REQUEST_URI'] will be the URI of the original page requested. Do your database lookup, and if you find a page you want to redirect do, use header("Location: " . $wherever) to redirect to it.



回答2:

The simplest way that I can think of would be to use mod_rewrite (link is to a great introduction tutorial) to redirect ALL incoming requests to a single PHP script (or use a flag so that this redirect only happens if the request is for a file that does not exist), with the requested address passed as part of the query string. From there, have the PHP script look up where that request should go to, and redirect to it.

So if someone tries to open http://www.foo.com/old_page.html, the mod_rewrite would send to something like http://www.foo.com/redirect.php?page=old_page.html. redirect.php then does a database lookup to see what the new address for "old_page.html" is, and redirects to there.



回答3:

Instead of creating a database, why not just put a redirect into a page with the old URL (ie. old_page.html)?

Since you are obviously doing this on a case-by-case basis with the database entries, you could just do it as a case-by-case basis with the pages.

You could write a quick perl script or whatever you like to generate these html pages for you given an old page's name and the URL of the new page.



回答4:

You could also use a RewriteMap:

old_page new-page
# …

But you will need to define that map in you httpd.conf (or virutal host configuration):

RewriteMap oldtonew txt:/path/to/file/map.txt

You can then use that map in your .htaccess file:

RewriteCond ${oldtonew:$1} .+
RewriteRule ^(.*)\.html$ /%0.html [L,R=301]