简体   繁体   中英

add trailing slash to slug url

I have this rewrite condition I use it to grab the slug url and search for a blog post like this:

http://localhost:8080/blog/my-first-post

So I grab the slug and then look for the post and display it. Right now it accepts this two forms

http://localhost:8080/blog/my-first-post
http://localhost:8080/blog/my-first-post/

How should I change the .htaccess so it always adds or redirects with the slash at the end.

And how should I change it to remove the slash always?

Here is the .htaccess I have now which I have it in the blog directory:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>

You can replace your current htaccess code by this one

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /blog/

    # add trailing slash
    RewriteCond %{REQUEST_URI} !/$
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ $1/ [R=301,L]

    # remove trailing slash
    #RewriteCond %{REQUEST_FILENAME} !-d
    #RewriteRule ^(.+?)/$ $1 [R=301,L]

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>

Right now, it adds trailing slash. If you want to remove it, comment add trailing slash block lines and uncomment remove trailing slash block lines

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM