Redirection with .htaccess and PHP

Image for post
Image for post
Photo by Safar Safarov on Unsplash

I’ve been starting a new blog on my domain, for which I wanted to use the ‘blog’ subdomain. However, this subdomain was already in use for all my coding-related stuff. So, I decided to move my current blog from /blog to /coding and upload my new blog to /blog. So far, so good. Now I have both of my blogs up and running. There’s just one problem: Any incoming traffic to existing posts on my blog would resolve to 404s. In todays post, I’m gonna show you how I resolved that issue.

First of all, my domain runs on an apache server, so I decided to capture all 404s and redirect them to a specific errorpage. To do this, I needed to add the following statement to my .htaccess file, which is located in the root directory of my webspace.

Note that it’s important to use a relative path to the php file. If you use an absolute path, you will override the query-string variable in php, which you might need later for the redirect. I added the notfound.php file to my blog-directory, from where it will be resolved correctly. The file looks like this:

All it does is it takes the request uri, and appends it to the new domain, passing a 301 — permanent redirect back to the browser. And that’s it already — My old links are still working and I can work on both blogs separately.

Originally published at https://coding.mjurtz.com on November 7, 2020.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store