Need to remove .html file extension and duplicate

2019-08-30 23:03发布

I have a .htaccess file with the contents below, that removes the .html file extension for all of my website's pages.

Options +MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC,L]
RewriteEngine On
RewriteCond %{SERVER_PORT} !=443
RewriteCond %{HTTP_HOST} ^(www\.)?james-lee\.io$ [NC]
RewriteRule ^$ https://www.james-lee.io%{REQUEST_URI} [R,L]

My links now look like www.james-lee.io/resume/resume when before they looked like www.james-lee.io/resume/resume.html. I would like to remove the folder name so the name of the folder is not duplicated by the name of the file minus the .html and the final result looks like www.james-lee.io/resume.

I have seen similar questions but not exactly what I am looking for.

1条回答
放荡不羁爱自由
2楼-- · 2019-08-30 23:54

So I have done this task! Try this code:

RewriteCond %{REQUEST_URI} ^/(.*)/(.*)$
RewriteCond %{DOCUMENT_ROOT}/%1 -d
RewriteCond %{DOCUMENT_ROOT}/%1/%2 -f
RewriteCond %1::%2 ^(.*)::\1$
RewriteRule ^(.*)$  /%1 [R,L]

RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)/(.*)$ /$1/$1 [END]

Now I try to explain this rules.

  1. first line: you do request like /folder/file
  2. second line: check if /folder/ real existing folder
  3. third line: check if /folder/file is real existing file
  4. fourth line: I use notation %1::%2 because backreferences can only be used in the left part of RewriteCond. But it possible to reuse left part in pattern of the right part. So, in the "^(.*)::\1$" I check all before ::. Then I have result at the \1 backreference. So, if folder is equal to file, text after :: will be equal to %2.
  5. Next I just redirect to the result (/folder or /file, doesn't matter, because both are equal)

But if folder == file, redirect will be always to the directory. So, next I check, if redirect result is existing dir and change the link.

Request example: http://yourdomain/test/test

(this will be redirected to http://yourdomain/test, but will reference to original link)

I hope, I explain clearly, but if you have any questions, I would glad to answer.

Thank you for insteresting task!

P.S. see also %N backreference inside RewriteCond

UPDATED. Your htaccess have to be like below:

RewriteEngine on

RewriteCond %{SERVER_PORT} !=443
RewriteCond %{HTTP_HOST} ^(www\.)?james-lee\.io$ [NC]
RewriteRule ^$ https://www.james-lee.io%{REQUEST_URI} [R,L]

RewriteCond %{REQUEST_URI} ^/(.*)/(.*)$
RewriteCond %{DOCUMENT_ROOT}/%1 -d
RewriteCond %{DOCUMENT_ROOT}/%1/%2\.html -f
RewriteCond %1::%2 ^(.*)::\1$
RewriteRule ^(.*)$  /%1 [R,L]

RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)/(.*)$ /$1/$1.html [END]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC,L]
查看更多
登录 后发表回答