.htaccessurlurl-rewritingpretty-urls

URL Beautification using .htaccess


in search of a more userfriendly URL, how do i achieve both of the following, elegantly using only .htaccess?

/de/somepage
going to /somepage?ln=de

/zh-CN/somepage#7
going to /somepage?ln=zh-CN#7

summary:
/[language]/[pagefilenameWithoutExtension][optional anchor#][a number from 0-9]

should load (without changing url)
/[pagefilenameWithoutExtension]?ln=[language][optional anchor#][a number from 0-9]

UPDATE, after provided solution: 1. exception /zh-CN/somepage should be reachable as /cn/somepage 2. php generated thumbnails now dont load anymore like:
img src="imgcpu?src=someimage.jpg&w=25&h=25&c=f&f=bw"


Solution

  • RewriteRule ^([a-z][a-z](-[A-Z][A-Z])?)/(.*) /$3?ln=$1 [L]
    

    You don't need to do anything for fragments (eg: #7). They aren't sent to the server. They're handled entirely by the browser.

    Update: If you really want to treat zh-CN as a special case, you could do something like:

    RewriteRule ^zh-CN/(.*) /$1?ln=zh-CN [L]
    RewriteRule ^cn/(.*) /$1?ln=zh-CN [L]
    RewriteRule ^([a-z][a-z])/(.*) /$2?ln=$1 [L]