I have a NextJS website statically served on an apache server and using an .htaccess file to setup the routing rules etc. This files looks like this
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{ENV:HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^([^/]+)/$ 1ドル.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/$ 1ドル.html
RewriteRule ^([^/]+)/([^/]+)/$ /1ドル/2ドル.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /1ドル/ [L,R=301]
</IfModule>
The problem I'm facing:
My internal links look like example.com/page-1, so when I redirect from example.com to example.com/page-1 everything is working well.
But when I target this page directly from it's URL or reload the page the server is adding a extra trailing slash to the URL. e.g. example.com/page-1/
This causes duplicate content within search engines /
What I'm looking for:
I'm looking for a solution in my .htaccess that prevents the server from adding a trailing slash on reloading the page. But URL's like example.com/about/page-1 should keep working.
1 Answer 1
I found a solution for my own problem. The problem was causes because I copied this .htaccess from an old React project where it was supporting the react-router.
Within my NextJS project I only had to remove the .html extension inside the .htaccess file. See example below:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{ENV:HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ 1ドル.html [NC,L]
</IfModule>
1 Comment
.html extension, it adds it (the opposite). (The .html extension has - presumably - already been removed in your links.) Aside: This appends the .html on any URL that does not map to a file, so /anything is rewritten to /anything.html - regardless of whether that file exists or not. Ideally, you would check that the .html file exists first before rewriting the request. The <IfModule> wrapper serves no purpose here. And no need to repeat the RewriteEngine directive.
trailingSlash: false,)