Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

regex - htaccess clean urls & replacing whitespaces and %20 with -

I'm strugling to make this work. At the moment my htaccess contains the following code:

#Debugging - Error reporting
php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on

#Commpression
<ifmodule mod_deflate.c="">
    <filesmatch ".(js|css|html|png|jpg|jpeg|swf|bmp|gif|tiff|ico|eot|svg|ttf|woff|pdf)$"="">
        SetOutputFilter DEFLATE
    </filesmatch>
</ifmodule>

Options All -Indexes +FollowSymLinks -MultiViews

<IfModule mod_rewrite.c>
    # Turn mod_rewrite on
    RewriteEngine On
    RewriteBase /

    #RewriteCond %{THE_REQUEST} (s|%20)
    RewriteRule ^([^s%20]+)(?:s|%20)+([^s%20]+)((?:s|%20)+.*)$ $1-$2$3 [N,DPI]
    RewriteRule ^([^s%20]+)(?:s|%20)+(.*)$ /$1-$2 [L,R=301,DPI]

    #RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} !^.*.(png|jpg|bmp|gif|css|js)$ [NC]
    RewriteRule ^([^/]+/?.+)$ /index.php?req=$1 [L,QSA]

</IfModule>

Everything works great except 1 thing if I try this url for example:

http://www.domain.com/ test/

the browser translates it like to: http://www.domain.com/%20test/ basically after the domain if the path starts with a whitespace or a %20 it fails. can anyone please point to a solution where the starting spaces will be removed ?

UPDATE

The goal:

www.domain.com/   this is a      test      /   hello there     /

or

www.domain.com/   this is a      test      

to

www.domain.com/this-is-a-test/ or www.domain.com/this-is-a-test/hello-there

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I am guilty of writing that code more than 2 years back :P

That can be hugely simplified by this code:

# remove spaces from start or after /
RewriteRule ^(.*/|)[s%20]+(.+)$ $1$2 [L]

# remove spaces from end or before /
RewriteRule ^(.+?)[s%20]+(/.*|)$ $1$2 [L]

# replace spaces by - in between
RewriteRule ^([^s%20]*)(?:s|%20)+(.*)$ $1-$2 [L,R]

PS: Must add that you need to fix the source of these URLs also because it is really not normal to be getting URLs like this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...