Forum Moderators: phranque
Trying to figure this out, just can't wrap my head around it.
I have a current URL structure that looks like this:
[mysite.com?my-articles.php?id=74...]
I have gone through and converted the titles of my articles to slugs, such as:
Title of Article
to
title-of-article
What I can't figure out is:
How can I automatically 301 redirect the current articles to a format like this:
[mysite.com...]
I know how to do it using the variables in the original URL - but I'm not sure how to include the "title-of-article" slug that I created.
Can anyone help? Thanks.
Be sure that the script checks the original request as received from the browser to be sure the browser requested the old-style URL, before you redirect the request. This is the easiest way to find out if the requested URL was the old-style dynamic URL or if you're just looking at the rewritten filepath.
If that's not clear, then consider that before going to 'friendly' URLs, your URL-paths were identical to your filepaths. Now the URL is example.com/title-of-article-74/ and the filepath is /my-articles.php?id=74 -- They are 'associated' but not identical.
When a request for /title-of-article-74/ arrives at the server, you're currently rewriting that to the /my-articles.php?id=74 filepath, so this is the URL/file-path that your script will 'see'. You'll need to check to see if it 'sees' this dynamic URL/file-path because of your rewrite, or because that was the originally-requested URL. Only in the latter case can you redirect; If you redirect unconditionally, then you'll get an 'infinite' rewrite/redirect loop.
One way to solve this is for your rewrite rule to check the variable %{THE_REQUEST} using a RewriteCond and pass the client-requested URL to your script in the query string. For your example URLs, the two possibilites would then be /my-articles.php?id=74&client_URL=my-articles.php?id=74 (needs to be 301-redirected) or /my-articles.php?id=74&client_URL=title-of-article-74/ (must not be redirected).
And actually, if you modify your main script, then you could leave off the id name/value pair in your rewrite, because you can get that from the client-requested URL within the script; your original id= variable is now somewhat redundant. Otherwise, you'll need two scripts: One to call if the requested URL is the old style, and then your current script to call if the URL is the proper new-style URL.
Jim