路由(htaccess)子文件夹到文件

时间:2017-01-04 02:28:06

标签: apache .htaccess redirect mod-rewrite url-rewriting

我正在处理附加组件(用于CMS)以包含新闻。为了防止创建许多索引文件,我尝试使用htaccess重定向,但对我来说似乎很复杂; - )

我在根目录中使用.htaccess作为CMS:

ErrorDocument 404 404.php

RewriteEngine On

# Redirect from http to https
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteCond %{HTTP_HOST} !^domain.tld$ [NC]
RewriteRule ^(.*)$ https://domain.tld/$1 [L,R=301]

# If called directly - redirect to short url version
RewriteCond %{REQUEST_URI} !/page/intro.php
RewriteCond %{REQUEST_URI} /page
RewriteRule ^page/(.*)$ /$1 [L,R=301]

# Send the request to the index.php for processing
RewriteCond %{REQUEST_URI} !^/(page|backend|framework|include|languages|media|account|search|temp|templates/.*)$
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([\/\sa-zA-Z0-9._-]+)$ /index.php?$1 [QSA,L]

# allow robots.txt (all other txt are denied before)
RewriteCond %{REQUEST_URI} !/robots\.txt$ [nocase]
RewriteRule \.txt$  -  [forbidden,last]

目前的结构:

--> page/
----> folder1/accessfile.php
----> folder1/.htaccess

我想重定向:

 /page/folder1/accessfile/lorem/ipsum 

和     / page / folder1 / accessfile / lorem / ipsum /#(不存在的文件夹)

到:

/page/folder1/accessfile.php

我尝试在page/folder1/.htaccess中使用此功能:

Options +FollowSymLinks
RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule ^accessfile/.*$ ./accessfile.php

但这不起作用: - (

1 个答案:

答案 0 :(得分:0)

将htaccess文件放在根目录旁边的page/目录中。如果您的htaccess文件已驻留在那里,请将重写规则放在 # If called directly - redirect to short url version行之前。

这就是你需要的:

Options +FollowSymLinks

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteBase /

    # Make sure it's not an actula file/dir being accessed
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    # Make sure request uri does not contain the actual file 
    # name, avoiding recursive rewrite loops
    RewriteCond %{REQUEST_URI} !accessfile\.php
    RewriteRule page/folder1/accessfile/?(.*)? /page/folder1/accessfile.php?q=$1 [R,L,QSA]
</IfModule>
## Results
# page/folder1/accessfile             => page/folder1/accessfile.php?q=
# page/folder1/accessfile/foo         => page/folder1/accessfile.php?q=foo
# page/folder1/accessfile/foo/bar     => page/folder1/accessfile.php?q=foo/bar
# page/folder1/accessfile/foo/bar/baz => page/folder1/accessfile.php?q=foo/bar/baz

如您所见,为方便起见,重写规则将请求URI重写为查询字符串参数。因此,PHP文件可以使用$_GET['q']访问传递的数据。

如果您希望保留干净的URL,并将请求重写到幕后的php文件中,请删除R标记。

相关问题