Search code examples
.htaccesspermalinks

htaccess mulitlevel permalinks?


Hello I wonder if you can help me with a specific htaccess file.

index#?city=antwerpen should become /antwerpen

detailfeest#?city=antwerpen&id=123456789 should become /antwerpen/123456789

Also forcing www, removing file extensions and trailing slashes. Could anyone perfect this code?

Options +FollowSymLinks
RewriteEngine On

RewriteBase /

# Force WWW prefix
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} ^([^.]+)\.([a-z]{2,4})$ [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


# Remove .php extension
RewriteCond %{THE_REQUEST} ^GET\ /[^?\s]+\.php
RewriteRule (.*)\.php$ /$1 [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^/(.+)/$
RewriteCond %{DOCUMENT_ROOT}/%1.php -f
RewriteRule ^(.*)/$ $1.php [L]

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

# Css, js, img paths + pretty links
RewriteCond %{REQUEST_FILENAME} !/(admin|css|fonts|img|js|mail)/
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]*)(.*)$ index#?city=$1
RewriteRule ^([^/]*)(.*)$ detailfeest#?city=$1&id=$2
RewriteRule ^(.+)/(admin|css|fonts|img|js|mail)/(.*)$ $2/$3 [L]

---- EDIT ----

I figured out how to force the relative paths — thank you, stack overflow for helping me understand this a little more. For future reference, I found this question particularly helpful.

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !(admin|css|fonts|img|js|mail).+$
RewriteRule ^(.*)/(admin|css|fonts|img|js|mail)/(.*)$ $2/$3 [L]


RewriteRule ^index/([a-z]+) index.php?city=$1
RewriteRule ^detailfeest/([a-zA-Z0-9-]+)/([a-zA-Z0-9-]+) detailfeest.php?  city=$1&id=$2
RewriteRule ^detailclub-organisatie/([a-zA-Z0-9-]+)/([a-zA-Z0-9-]+)/([a-zA-Z0-9-]+) detailclub-organisatie.php?city=$1&id=$2&club_id=$3

Solution

  • To remove the trailing slash use:

    RewriteEngine on
    RewriteRule (.+)/$ /example/$1 [L,R=301]
    

    If located in a directory use:

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

    To force WWW use:

    Options +FollowSymLinks
    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^example.com[nc]
    RewriteRule ^(.*)$ http://www.example.com/$1 [r=301,nc]
    

    http://index#?city=antwerpen to http://index/antwerpen

    RewriteEngine On
    RewriteRule ^([^/]*)\.html$ #?city=$1 [L]
    

    http://detailfeest#?city=antwerpen&id=123456789 to http://detailfeest/antwerpen/123456789

    RewriteEngine On
    RewriteRule ^([^/]*)/([^/]*)\.html$ #?city=$1&id=$2 [L]