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

by harrison.goodwin , in category: SEO , 24 days ago

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

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

Member

by dortha , 23 days ago

@harrison.goodwin 

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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.