在Apache上进行Mod重写:更改所有网址
时间:2020-03-06 14:27:19 来源:igfitidea点击:
现在我正在做这样的事情:
RewriteRule ^/?logout(/)?$ logout.php RewriteRule ^/?config(/)?$ config.php
我宁愿有一个规则对每个网址执行相同的操作,因此我不必在每次添加新文件时都继续添加它们。
另外,如果可能的话,我喜欢将'/ config / new'与'config_new.php'匹配。我猜正则表达式可以让我完成此任务吗?
感谢堆栈成瘾者!
解决方案
尝试:
RewriteRule ^ /?(\ w +)/?$ $ 1.php
$ 1是第一个捕获的字符串在方括号中的内容。不需要在第二个斜杠周围的括号。
编辑:对于其他匹配项,请尝试以下操作:
RewriteRule ^ /?(\ w +)/(\ w +)/?$ $ 1_ $ 2.php
Mod重写无法(潜在地)像问题第二部分中那样进行无限替换。但是请查看《 Apache URL重写指南》底部的"外部重写引擎":
External Rewriting Engine Description: A FAQ: How can we solve the FOO/BAR/QUUX/etc. problem? There seems no solution by the use of mod_rewrite... Solution: Use an external RewriteMap, i.e. a program which acts like a RewriteMap. It is run once on startup of Apache receives the requested URLs on STDIN and has to put the resulting (usually rewritten) URL on STDOUT (same order!). RewriteEngine on RewriteMap quux-map prg:/path/to/map.quux.pl RewriteRule ^/~quux/(.*)$ /~quux/${quux-map:} #!/path/to/perl # disable buffered I/O which would lead # to deadloops for the Apache server $| = 1; # read URLs one per line from stdin and # generate substitution URL on stdout while (<>) { s|^foo/|bar/|; print $_; } This is a demonstration-only example and just rewrites all URLs /~quux/foo/... to /~quux/bar/.... Actually you can program whatever you like. But notice that while such maps can be used also by an average user, only the system administrator can define it.
我会做这样的事情:
RewriteRule ^/?(logout|config|foo)/?$ .php RewriteRule ^/?(logout|config|foo)/(new|edit|delete)$ _.php
我更愿意明确列出要匹配的网址,这样我就不必担心静态内容或者以后添加不需要重写为php文件的新内容。
如果所有子URL对所有根URL(" book / new"," movie / new"," user / new")均有效,则上述方法是可以的,但是如果我们希望根据根操作使用不同的子URL,则效果不是很好(logout / new
没有多大意义)。我们可以使用更复杂的正则表达式来解决此问题,也可以将所有内容路由到单个php文件,该文件将根据网址确定要包含和显示的文件。