How do I exclude .html and add / at the end of the url in htaccess?

by harrison.goodwin , in category: SEO , a year ago

How do I exclude .html and add / at the end of the url in htaccess?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

3 answers


by dortha , a year ago


To exclude the ".html" extension from URLs and add a trailing slash at the end of URLs, you can use the following rules in your .htaccess file:

RewriteEngine On

# Remove .html extension from URLs
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*)/$ $1.html [L]

# Add trailing slash to URLs
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) $1/ [R=301,L]

The first block of code removes the ".html" extension from URLs, but only for files that exist and are not directories. This means that if you have a directory with the same name as a file with a ".html" extension, the directory will take precedence.

The second block of code adds a trailing slash to URLs, but only for URLs that are not already directories or files. This ensures that you won't have a redirect loop if you try to access a directory or file without a trailing slash.

Note that these rules assume that your URLs have a consistent structure where the ".html" extension is always present and a trailing slash is always missing. If your URLs have a different structure, you may need to modify the rules accordingly.

by creola.ebert , 5 months ago


Make sure to place the .htaccess file in the root directory of your website.

by cameron_walter , 5 months ago


This .htaccess file is typically placed in the root directory of your website. It will affect all URLs within that directory and its subdirectories. Make sure you have enabled the RewriteEngine by adding RewriteEngine On at the beginning of your .htaccess file.