Friendly URLs spaces to hyphens & uppercase to lowercase

二次信任 提交于 2019-12-13 19:19:06

问题


I'd like to convert spaces in dynamic URLs to use hyphens, and if there are any uppercase letters in the URL then it would make them lowercase.

spaces to hyphens example

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

uppercase to lowercase example

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

My current .htaccess file rules.

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:


For space to hyphen conversion in your /article/ URIs you can try this rule:

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

Insert this rule just above Force a trailing slash rule.

PS: For case conversion you will need access to server config since case conversion would need a RewriteMap entry in Apache server config.



来源:https://stackoverflow.com/questions/20103413/friendly-urls-spaces-to-hyphens-uppercase-to-lowercase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!