Search code examples
apache.htaccess

add .html to url but results 404 not found


Read this and bababa but sadly none of them can direct me how to debug.

I am trying to redirect below url https://example.com/hello to https://example.com/hello.html

Here is how I did

First

vim /etc/apache2/apache2.conf, set AllowOverride All in <Directory /var/www/>

Now is

<Directory />
        Options FollowSymLinks
        AllowOverride None
        Require all denied
</Directory>

<Directory /usr/share>
        AllowOverride None
        Require all granted
</Directory>

<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
</Directory>

Second

sudo service apache2 restart

Third

Create .htaccess in public_html and below code

<IfModule mod_rewrite.c>
  
Options FollowSymLinks

RewriteEngine On
RewriteCond %{REQUEST_URI} !^.*\.html$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ %{REQUEST_FILENAME}.html

</IfModule>

But still return 404 not found like below.

enter image description here

Any suggestion or any parts I am missing to config apache? Thanks


------ANSWER------

Missed the configuration for mod_rewrite. Can check this post


Solution

  • You are adding .html at the end of %{REQUEST_FILENAME} which will aways cause a 404 since %{REQUEST_FILENAME} represents full filesystem path not the URI path.

    You should use this rule:

    RewriteEngine On
    
    RewriteCond %{REQUEST_URI} !\.html$ [NC]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . %{REQUEST_URI}.html [L]
    

    or even better:

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}.html -f
    RewriteRule ^(.+?)/?$ $1.html [L]