How to redirect static to dynamic url using .htaccess (on Wordpress site)
I took the old site / domain and set up the new site using Wordpress. The WP installation rewrites the url for static ones as expected.
At the same time, I want to keep the old pages as they have inbound links. I am not interested in the 301st output of them to the "new" pages.
Old url structure /index.php?id=123
that I suspect is causing WP.htaccess file issue. For reference, it looks like this:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
I tried to add the following:
RewriteRule ^([0-9]+).html index.php?id=$1 [R,L]
Does not work. Just redirects to site.com/?id=123
and shows the first page.
I must add that I only plan on adding these new pages as normal static HTML files in 123.html, 321.html, etc. format.
How do I use .htaccess to work together with a WP installation and what WP puts into the .htaccess file?
To clarify:
I want a static HTML page to 123.html
be index.php?id=123
. When you access it index.php?id=123
, it should call 123.html
, but show index.php?id=123
in the address bar. If you access 123.html
, then it should 301 before index.php?id=123
.
source to share
To match the url with the verification to the actual file you need to use RewriteCond
to match the string itself (like RewriteRule
):
Something along these lines should do it:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
# retrieve X.html when index.php?id=X is requested
RewriteCond %{REQUEST_FILENAME} index\.php
RewriteCond %{QUERY_STRING} ^id=([0-9]+)$
RewriteCond %1.html -F
RewriteRule .* %1.html? [L]
# standard WordPress routing
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
First, you will check if you have a query for index.php with a querystring like id = X.
It then checks to see if a file named X.html exists; I'm not 100% happy with the fact that I should be using a hungrier sub-task file with the -F filesystem rather than the standard -f , but I don't see the path around it in .htaccess in this case.
If X.html does exist, will it fetch that file, leaving the url as index.php? id = X.
However, if this file does not exist, it will fall back to the standard WordPress version with no file , no directory in index.php
I'm not a WordPress expert, but this should work; I think the main WordPress controller uses $_SERVER['REQUEST_URI']
to define the action.
Note. ... However, this will prevent people from accessing 123.html directly by going to the url www.site.com/123.html - I kept falling into infinite loops and Apache 500 errors trying to prevent this: |
source to share