I have a URL structure like this -
https://example.com / folder / subfolder / files.html
I have many files in the subfolder. I want to remove the 'subfolder' from the URL.
I have tried some of the StackOverflow solutions. but not succeeded.
Also please tell me where to paste the .htaccess code. in the .htaccess file which is located in 'folder' or in 'subfolder'.
edit
folder/htaccess
RewriteEngine On
RewriteCond {REQUEST_FILENAME} !-f
RewriteCond {REQUEST_FILENAME} !-d
RewriteRule ^(. )/?$ /folder/subfolder/$1 [L]
subfolder/htaccesss
RewriteEngine On
RewriteRule (. ) /folder/$1 [L,R]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.] )\.html [NC]
RewriteRule ^ %1 [R,L,NC]
RewriteCond %{REQUEST_FILENAME}.html-f
RewriteRule ^ %{REQUEST_URI}.html[L]
CodePudding user response:
You can use the following rule in your /folder/. htaccess
:
RewriteEngine On
RewriteCond {DOCUMENT_ROOT}/$1 -f [OR]
RewriteCond {DOCUMENT_ROOT}/$1 -d
RewriteRule ^(. )/?$ /folder/subfolder/$1 [L]
If the rule above fails to work, then use the following instead
RewriteEngine On
RewriteCond %{REQUEST_URI} !/folder/subfolder/
RewriteRule ^(. )/?$ /folder/subfolder/$1 [L]
Remember to place the rule at the top of your htaccess or before other directives and put it in htaccess in your /folder
directory.
EDIT :
If you also want to redirect your old URLs to the new one , for example /folder/subfolder/file.html
to /folder/file.html
, put the following rule in htaccess in folder/subfolder
RewriteEngine On
RewriteRule (. ) /folder/$1 [L,R]
Remember to place the code above in htaccess in your subfolder
and when you are sure the rule is working, change R
to R=301
to make the redirection permanent as it avoids the duplicate content issues in search engines.
Edit :
If the above solution isn't working for you, as you said in comments you are getting 404
error on redirection. The error is there because the requested file is being rewritten to a non-existentpath
/folder/file.html. You can solve this by removing your
/folder/subfolder/. htaccessfile and only use one single htaccess in
/folder/` with the following contents :
RewriteEngine On
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^subfolder/(. )/?$ /folder/$1 [L,R]
RewriteCond %{REQUEST_URI} !/folder/subfolder/
RewriteCond %{REQUEST_URI} !\.(css|js|jpg|gif|png|jpeg)$
RewriteRule ^(. )/?$ /folder/subfolder/$1 [L]