我的应用程序最多可以使用6个查询变量,可以在“干净”的网址中重写。 所以我在.htaccess文件中设置URL重写,哪种工作(一些边缘情况可能与此代码无关)但我想知道:有更有效的编写方式吗?
<IfModule mod_rewrite.c>
RewriteEngine on
Options +FollowSymLinks
# if the following conditions are met, SKIP the rewriteRules.
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_URI} ^/v2/(_admin/|_css/|_js/|phpmyadmin/|_img/) [NC]
RewriteRule . - [L]
# Externally redirect to add missing trailing slash
RewriteRule ^(([a-z0-9._\-]+/)*[a-z0-9_\-]+)$ http://%{HTTP_HOST}/$1/?%{QUERY_STRING} [NC,R,L]
# SIX PARAMS
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$ index.php?section=$1&item=$2&menu=$3&content=$4&id=$5&title=$6&%{QUERY_STRING} [NC,L]
# FIVE PARAMS
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$ index.php?section=$1&item=$2&menu=$3&content=$4&id=$5&%{QUERY_STRING} [NC,L]
# FOUR PARAMS
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$ index.php?section=$1&item=$2&menu=$3&content=$4&%{QUERY_STRING} [NC,L]
# THREE PARAMS : projects/touch/texts/
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ index.php?section=$1&item=$2&menu=$3&%{QUERY_STRING} [NC,L]
# TWO PARAMS: downloads
RewriteRule ^downloads/([^/]+)/$ index.php?section=downloads&item=$1&%{QUERY_STRING} [NC,L]
# TWO PARAMS:
RewriteRule ^([^/]+)/([^/]+)/?$ index.php?section=$1&item=$2&%{QUERY_STRING} [NC,L]
# TAG URL : index.php?tag=url+encoded+keyword
RewriteRule ^tag/([a-z0-9_\-]+)/$ index.php?tag=$1&%{QUERY_STRING} [NC,L]
# ONE PARAM
RewriteRule ^([a-z0-9_\-]+)/$ index.php?section=$1&%{QUERY_STRING} [NC,L]
</IfModule>
答案 0 :(得分:1)
一般情况下它看起来不错,但可以进行一些改进,例如
QSA
(查询字符串追加)标记并避免一直添加%{QUERY_STRING}
\w
代替[A-Za-z-9_]
修改后的代码:
Options +FollowSymLinks -MultiViews
RewriteEngine on
# if the following conditions are met, SKIP the rewriteRules.
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_URI} ^/v2/(_admin/|_css/|_js/|phpmyadmin/|_img/) [NC]
RewriteRule . - [L]
# Externally redirect to add missing trailing slash
RewriteRule [^/]$ %{REQUEST_URI}/ [R,L]
# SIX PARAMS
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$ index.php?section=$1&item=$2&menu=$3&content=$4&id=$5&title=$6&%{QUERY_STRING} [NC,L]
# FIVE PARAMS
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$ index.php?section=$1&item=$2&menu=$3&content=$4&id=$5&%{QUERY_STRING} [NC,L]
# FOUR PARAMS
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$ index.php?section=$1&item=$2&menu=$3&content=$4 [QSA,NC,L]
# THREE PARAMS : projects/touch/texts/
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ index.php?section=$1&item=$2&menu=$3 [QSA,NC,L]
# TWO PARAMS: downloads
RewriteRule ^downloads/([^/]+)/$ index.php?section=downloads&item=$1 [QSA,NC,L]
# TWO PARAMS:
RewriteRule ^([^/]+)/([^/]+)/?$ index.php?section=$1&item=$2 [QSA,NC,L]
# TAG URL : index.php?tag=url+encoded+keyword
RewriteRule ^tag/([\w-]+)/$ index.php?tag=$1 [NC,L,QSA]
# ONE PARAM
RewriteRule ^([\w-]+)/$ index.php?section=$1 [L,QSA]