htaccess rewrite rules to remove multiple subfolders from a URL

▼魔方 西西 提交于 2020-03-23 02:07:22

问题


Due file system sub-directory constraints I will most likely reach I want to separate the /users folder into /users/a/username, /users/b/username, /users/c/username, etc.

So the data on the server for a user would be in: www.domain.com/users/a/username/, www.domain.com/users/b/username/, etc

I want the URL to be: www.domain.com/users/username/

Optionally to avoid duplicate content a 301 redirect from www.domain.com/users/a/username/ to www.domain.com/users/username/ would also be good.

Currently I have a rewrite for a single sub-directory (see below) but I'm confused how this can be done efficiently for all of the alphabetical sub-directories.

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^users/(.*)$ users/a/$1 [L,NC]

I have checked this site and all seem to hide the first sub-directory e.g. domain.com/folder1/filename.html => domain.com/filename.html but nothing in more depth.


回答1:


Put this code in your htaccess (which has to be in root folder)

Options -Indexes -MultiViews

RewriteMap lowercase int:tolower    # this line in your apache file configuration
RewriteEngine On

RewriteCond %{THE_REQUEST} \s/users/[a-z]/([^/\s]+)\s
RewriteRule . /users/%1/? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^users/([A-Za-z])([^/]+)/$ /users/${lowercase:$1}/$1$2/ [L]


来源:https://stackoverflow.com/questions/25353101/htaccess-rewrite-rules-to-remove-multiple-subfolders-from-a-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!