Skip to main content Accessibility Feedback

How to redirect if a page doesn't exist with Apache

Over a decade ago, I decided I wanted my article URLs to live at my site’s root path / instead of a subpath (like /blog or /articles) “for SEO purposes.”

That made sense when I had a few dozen articles and hosted with WordPress.

Today, I have nearly 3,000 articles generated as a flat HTML files with Hugo, and navigating my file system on the server is an unruly mess!

I finally decided to fix this, moving all of my articles to the /articles subdirectory.

But I also wanted to sure that all of the many, many links to past articles continued to work. That’s easy to do when they already live in a subdirectory, and much harder when they’re at the root.

I didn’t want to go through an individually create redirects for all 2,929 articles. But I also can’t just blanket redirect everything in the root to /articles, because I have lots of other valid root pages.

Luckily, so .htaccess magic came to the rescue!

<IfModule mod_rewrite.c>
    # 1. Enable the rewrite engine
    RewriteEngine On

    # 2. If the request is...
    #    - NOT already a /articles page, and
    #    - NOT a real file (-f), or
    #    - NOT a real directory (-d).
    RewriteRule ^(articles)($|/) - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    # Redirect to your home page (or another page) first
    RewriteRule ^(.*)$ /articles/$1 [L,R=301]
</IfModule>

This redirects all root requests to /articles/<requested path>, but…

If the requested root page already exists, it doesn’t run. It also doesn’t run if the requested URL doesn’t already contain /articles/, which prevents recursive redirects.

Feel free to steal and modify as needed!