I have kind of an unusual setup with my website:
site.tld
= Gatsby Website with some static pages like /example1 and /example2, etc.site.tld/blog
= A WordPress website
Now I wanted to have users visit a new page site.tld/mynewpage
which ACTUALLY is a page on the WordPress website. So the actual URL is site.tld/blog/mynewpage
.
To achieve that I have defined this rule:
RewriteRule ^mynewpage/$ /blog/mynewpage/ [L]
Which kind of works. It lets me successfully see the desired wordpress page, when I browse to site.tld/mynewpage
.
My expactation would’ve been that if I now browse to site.tld/blog/mynewpage
, it would either give me a 404 or it would "auto-redirect" to site.tld/mynewpage
. But none of that happens. The address bar still says site.tld/blog/mynewpage
and I see that page correctly. So now I have two links pointing to mynewpage
. For SEO thats not a big deal, since I can set the canonical URL to be site.tld/mynewpage
, but it bothers me, that this "old URL" site.tld/blog/mynewpage
is still around.
Is there a way to fix that? I naively tried to do a redirect from site.tld/blog/mynewpage
to site.tld/mynewpage
but that gave me a "too many redirects", which I think is because it’s an infinite loop.
Any help appreciated =)
2
Answers
Add 301 redirection to your old URL –
site.tld/blog/mynewpage
tosite.tld/mynewpage
301 redirection can be added via .htaccess like below
or you can try using the below code if you have custom php page
You need to make sure you only redirect "direct" requests back to the root and not the rewritten request by your existing rewrite in the root
.htaccess
file (which will result in a redirect loop).Add the following to the top of the
/blog/.htaccess
file:This assumes the URL has a trailing slash, as in your "working" rewrite directive. However, all your examples have omitted the trailing slash?
At first glance, this might "look" like it’s redirecting to the same URL, however, because the
.htaccess
file is in the subdirectory it does remove the subdirectory from the redirected URL. ie. It redirects from/blog/mynewpage/
to/mynewpage/
.The
RewriteRule
pattern matches the URL-path relative to the location of the.htaccess
file. So, since we are in the/blog
subdirectory, the regex^mynewpage/$
matches a request for/blog/mynewpage/
. And we redirect back to/mynewpage/
using the$0
backreference, which contains the URL-path that was matched by theRewriteRule
pattern.The check against the
REDIRECT_STATUS
environment variable ensures that only direct requests (from the client) are redirected and not rewritten requests by your existing rewrite.NB: Test first with a 302 (temporary) redirect to avoid caching issues.