Removing string from URL using .htaccess

2019-09-18 14:57发布

I have URLs in the form of example.com/pages/page1 and /example.com/pages/page2

Is there an easy way in .htaccess to get rid of the /pages/ section, so my URLs are:

example.com/page1

Thanks

标签: .htaccess
1条回答
叼着烟拽天下
2楼-- · 2019-09-18 15:42

If you have the ability to modify the DocumentRoot, it sounds like you would just need to set your DocumentRoot to /path/to/pages. However, if you can't do that then you can try this in .htaccess

RewriteEngine On
RewriteRule ^/(.*)$ /pages/$1 [L,QSA]

The above is generic and redirects everything to /pages. If your pages really are called "page1 page2 etc", then this is more specific:

RewriteRule ^/page([0-9]+)$ /pages/page$1 [L,QSA]

Remove the [L] if you have more rewrite rules to process. The [QSA] forwards along any other querystring parameters that may have been present.

EDIT: For users to enter example.com/pages/page1 to be redirected to example.com/page1:

RewriteEngine On
RewriteRule ^/pages/(.*)$ /$1 [L,QSA]

The above will redirect internally but not change the browser's address bar. If you want the address bar to change, informing the user that the redirect has happened, use [L,R=301,QSA] instead.

查看更多
登录 后发表回答