htaccess redirect non-existent directories to index.php

July 4, 2019 663 views
Apache LAMP Stack Ubuntu

Goal: have www.website.com/anything redirect to www.website.com
Issue: 404

I’ve meticulously followed: https://www.digitalocean.com/community/questions/htaccess-and-subdomain-issues

Confirmed:
Activate Mod_Rewrite ✓
Create new .htaccess file ✓
Allow use of .htaccess ✓
Restart Server every change ✓

My current .htaccess file:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /

Misc. Fun Facts:

  1. I have multiple domains on the same droplet: var/www/site1.com, var/www/site2.com, etc.
  2. One other domain is using an .htaccess file in its respective site.com/ folder (conflict?)
  3. I have tried keeping .htaccess file inside public_html and inside site.com level
1 comment
  • The tutorial link above was supposed to be this DO article, instead

    by Etel Sverdlov
    This tutorial goes over Mod_Rewrite, an apache module that allows you to manipulate URLS to provide shorter or more relevant ones. This tutorial will go over Activating Mod_Rewrite, Creating and Using the required .htaccess page, and setting up the URL rewrites.
1 Answer

Hi,

What I could suggest is first to make sure that your .htaccess file actually works. You could try causing a 500 error by adding some random characters on top of the file (Example: just pot asd on the first line of the .htaccess file and save it) then try accessing your site, if you get a 500 error then you would know that the .htaccess file actually works.

If this is the case, you could try modifying your redirect rule a little bit:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ /index.html [L]

If the .htaccess file is not working you would need to check your Apache config again.

Hope that this helps!
Bobby

  • Thanks for the consideration Bobby, still no luck.

    Update 1: if I do website.com/asdfghjkl - it successfully redirects! When I do /about it 404s.

    Note: I have an about.php file that you can view if you add the .php extension, but I want to be able to force /about to still show index.

    New things I’ve tried:

    Confirmed .htaccess is functioning ✓
    - 500 error on “asdf”
    Tried your redirect code ✓
    Renamed my other website .htaccess file ✓
    Triple checked Apache Config ✓

    <VirtualHost *:80>
        <Directory /var/www/website.com>
            Options Indexes FollowSymLinks Multiviews
            AllowOverride All
            Order allow,deny
            allow from all
        </Directory>
    

    Ran apache2ctl configtest (no error) ✓

    • Hello,

      Thanks for the clarification.

      In this case can you try with the following in your .htaccess file:

      ErrorDocument 404 http://yourdomain.com
      

      Let me know how it goes!
      [Bobby](httsp://bobbyiliev.com)

Have another answer? Share your knowledge.