使用 mod_rewrite 更改 url 路径

Tro*_*app 0 apache .htaccess mod-rewrite

是否可以使 URL 中的文件夹透明,如下例所示: example.com/test/ 更改为 example.com/

使用mod_rewrite?

我喜欢用文件夹来组织,但我想要一个漂亮干净的网址。

Alb*_*nez 5

您可以通过 mod_rewrite 将类似的内容放入.htaccess根文件夹的文件中来实现这一点:

RewriteEngine on

# the first condition is for avoiding an infinite loop
RewriteCond %{REQUEST_URI} !^/test/.*
RewriteRule ^(.*)$  /test/$1
Run Code Online (Sandbox Code Playgroud)

这将重定向到/test/请求的所有页面/文件/

如果您只想重定向某些文件,请使用更具体的规则:

RewriteEngine on

# the condition is for avoiding an infinite loop
RewriteCond %{REQUEST_URI} !^/test/.*
# redirecting only images files and files that start with "doc"
RewriteRule ^(.*\.(jpg|png|gif))$  test/$1 [L]
RewriteRule ^(doc.*)$  test/$1 [L]
Run Code Online (Sandbox Code Playgroud)

或者如果您想使用不同的文件夹:

RewriteEngine on

# the condition is for avoiding an infinite loop
RewriteCond %{REQUEST_URI} !^/images/.*
RewriteCond %{REQUEST_URI} !^/docs/.*
# redirecting only images files and files that start with "doc"
RewriteRule ^(.*\.(jpg|png|gif))$  images/$1 [L]
RewriteRule ^(doc.*)$  docs/$1 [L]
Run Code Online (Sandbox Code Playgroud)