首页 > 解决方案 > Apache Mod_Rewrite 请帮助

问题描述

我正在尝试编写一个 mod_rewrite 规则来满足以下条件:

/hire/audio --> /section?section=audio
/hire/audio/speakers --> /section?section=audio&sub_section=speakers
/hire/audio/speakers/jbl-jrx112m --> /detail?section=audio&sub_section=speakers&product=jbl-jrx112m
/hire/audio/speakers/d&b-q7-top --> /detail?section=audio&sub_section=speakers&product=d&b-q7-top
/hire/lighting/generic-lighting/thomas-par64-floor-can--> /detail?section=lighting&sub_section=generic-lighting&product=thomas-par64-floor-can
/hire/audio/speakers/all --> /section?section=audio&sub_section=speakers&filter=1
/hire/audio/speakers/1 --> /section?section=audio&sub_section=speakers&filter=1
/hire/audio/speakers/2 --> /section?section=audio&sub_section=speakers&filter=2

上面的列表并不详尽,但它让您了解我打算涵盖的所有可能的排列。

我尝试过的 htaccess 规则文件:

RewriteRule "^/hire/([0-9a-zA-Z-&]+)/([0-9a-zA-Z-&]+)/([0-9a-zA-Z-&]+)" "/detail?section=$1&sub_section=$2&product=$3" [NC, L]

标签: apache.htaccessmod-rewriteurl-rewritingfriendly-url

解决方案


使用您显示的示例,请尝试以下操作。请确保在测试您的 URL 之前清除您的浏览器缓存。

RewriteEngine ON
##Rule to handle(/hire/audio --> /section?section=audio).
RewriteRule ^hire/(audio)/?$ /section?section=$1 [NC,L]

##Rule to handle(/hire/audio/speakers --> /section?section=audio&sub_section=speakers).
RewriteRule ^hire/(audio)/(speakers)/?$ /section?section=$1&sub_section=$2 [NC,L]

##Rule to handle(/hire/audio/speakers/jbl-jrx112m --> /detail?section=audio&sub_section=speakers&product=jbl-jrx112m)
RewriteRule ^hire/(audio)/(speakers)/(jbl-jrx112m)/?$ /section?section=$1&sub_section=$2&product=$3 [NC,L]

##Rule to handle(/hire/audio/speakers/d&b-q7-top --> /detail?section=audio&sub_section=speakers&product=d&b-q7-top)
RewriteRule ^hire/(audio)/(speakers)/(d&b-q7-top)/?$ /section?section=$1&sub_section=$2&product=$3 [NC,L]

##Rule to handle(/hire/lighting/generic-lighting/thomas-par64-floor-can--> /detail?section=lighting&sub_section=generic-lighting&product=thomas-par64-floor-can)
RewriteRule ^(lighting)/(generic-lighting)/(thomas-par64-floor-can)/?$ /detail?section=$1&sub_section=$2&product=$3 [NC,L]

##Rule to handle(/hire/audio/speakers/(1|2) --> /section?section=audio&sub_section=speakers&filter=1)
RewriteRule ^(hire)/(audio)/(speakers)/(\d+)/?$ /section?section=$2&sub_section=$3&filter=$4 [NC,L]

##Rule to handle(/hire/audio/speakers/all --> /section?section=audio&sub_section=speakers&filter=1)  
RewriteRule ^hire/(audio)/(speakers)/all/?$ /section?section=$1&sub_section=$2&filter=1 [NC,L]

注意:这认为您在根目录中有文档(从后端提供),如果没有,请先/从每个规则的右侧删除。


推荐阅读