我在一台运行XAMPP的win8机器上。我用.htaccess文件设置了一个虚拟主机目录。我一直在研究如何重写url,我发现了RewriteEngine模块。在我的httpd.conf apache文件中,该模块已经启用:
LoadModule rewrite_module modules/mod_rewrite.so
下一步似乎是更新我的.htaccess文件,如下所示:
php_value register_globals off
DirectoryIndex default.php index.php
ErrorDocument 404 /filenotfound.html
RewriteEngine On
RewriteBase /
RewriteRule ^Home$ Default.php [L]
RewriteRule ^AboutMe$ About.php [L]
RewriteRule ^Work$ Work.php [L]
RewriteRule ^Blog//Categories$ Blog/Categories.php [L]
RewriteRule ^Blog//([^/.]+)/?$ Blog/Posts.php?val=$1 [L]
我已经回答了几个SO问题(配置和重写w/params),但即使是最简单的重写也无法正常工作。我已经重新启动了几次apache,但都没有结果。
当我在这里的时候,这是我的文件夹结构,可以归结为所有相关的内容:
root
.htaccess
Blog
AuthorPanel.php
Categories.php
Post.php
Posts.php
Default.php
About.php
Work.php
这些是我想要实现的重写(我已经尝试了大部分):
site.com/Default.php => site.com/Home
site.com/About.php => site.com/AboutMe
site.com/Blog/Categories.php => site.com/Blog/Categories
site.com/Blog/Posts.php?id=3&val=Android => site.com/Blog/Android
site.com//Blog/Post.php?id=4&title=Working+with+ActionBar => site.com/Blog/Working-with-ActionBar
更新1在httpd-vhosts.conf中,我甚至尝试使用重写引擎和重写规则,但也没有成功:
<VirtualHost *>
DocumentRoot "C:/Users/ben/Documents/PHP/benWIT"
ServerName benWIT.local
<Directory "C:/Users/ben/Documents/PHP/benWIT">
RewriteEngine on
Order allow,deny
AllowOverride all
Allow from all
Require all granted
RewriteRule ^Home$ Default.php [L]
RewriteRule ^AboutMe$ About.php [L]
RewriteRule ^Work$ Work.php [L]
</Directory>
</VirtualHost>
由于您使用的是htaccess,因此您需要确保在httpd.conf文件中将AllowOverride设置为All:
AllowOverride All
这将允许您使用htaccess文件。话虽如此,作为一般规则,如果您可以访问apache配置文件,则不希望使用htaccess文件或启用AllowOverride,因为它将使用更多资源来搜索目录和查找htaccess文件等。将更改放入httpd.conf文件或conf.d/example_host.conf要好得多。
另一个注意事项是,mod_rewrite被过度使用,对于大多数目的来说,它确实是过度使用。我建议您使用mod_alias(请参阅http://httpd.apache.org/docs/2.2/mod/mod_alias.html)相反。我应该指出,这只能在服务器配置或虚拟主机中使用,所以它在htaccess文件中不起作用。但如果你可以在两者之间做出选择,就应该优先考虑。
Alias /home /default.php
Alias /aboutme /about.php
Alias /work /work.php
AliasMatch /blog//([^/.]+)/? /blog/posts.php?val=$1
等等
以下是关于而非使用mod_rewrite的详细信息:http://httpd.apache.org/docs/2.2/rewrite/avoid.html