友好的URL空间连接到连字符&大写到小写

时间:2013-11-20 17:58:26

标签: php regex apache .htaccess mod-rewrite

我想将动态网址中的空格转换为使用连字符,如果网址中有任何大写字母,则会将它们设为小写。

空格到连字符示例

www.site.com/article/id/ 标题在这里 - > www.site.com/article/id/title-goes-here

大写到小写示例

www.site.com/article/id/ Title-Goes-Here - > www.site.com/article/id/title-goes-here

我当前的.htaccess文件规则。

RewriteEngine on

# add www before hostname
RewriteCond %{HTTP_HOST} ^site\.co$ [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=302,L,NE]

# if on article page, get slugs and make into friendly url
RewriteCond %{THE_REQUEST} \s/article\.php\?article_uid=([^&]+)&article_title=([^&\ ]+)
RewriteRule ^ /article/%1/%2/? [L,R=302,NE]

# if page with .php is requested then remove the extension
RewriteCond %{THE_REQUEST} \s/+(.+?)\.php[\s?] [NC]
RewriteRule ^ /%1/ [R=302,L,NE]

# Force a trailing slash to be added
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{THE_REQUEST} \s/+([^.]+?[^/.])[\s?] [NC]
RewriteRule ^ /%1/ [R=302,L]

# allow page direction to change the slugs into friendly seo URL
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule (?:^|/)article/([^/]+)/([^/]+)/?$ /webroot/article.php?article_uid=$1&article_title=$2 [L,QSA,NC]

# silently rewrite to webroot
RewriteCond %{REQUEST_URI} !/webroot/ [NC]
RewriteRule ^ /webroot%{REQUEST_URI} [L]

# .php ext hiding
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

1 个答案:

答案 0 :(得分:1)

对于/article/ URI中的空格到连字符转换,您可以尝试以下规则:

RewriteRule "^(article)/([^ ]*) +(.*)$" /$1/$2-$3 [L,R]

Force a trailing slash规则上方插入此规则。

PS:对于大小写转换,您需要访问服务器配置,因为大小写转换需要Apache服务器配置中的RewriteMap条目。