regexapache.htaccessurl-rewritingurlrewriter

I want create a url rewriting that get last folder and use it as file


The first folder (lang) is fixed and the "output" should be have only last folder with ".php" extension.

(Is possible to get first folder without create n rule for each language? "/en/blog/")

(Is possible add the slash at the end of the url if not present ? "/en/blog" --> "/en/blog/" )

Examples:

From:

/it/blog/

To:

/it/blog.php

From:

/it/blog/notizie/

To:

/it/notizie.php

From:

/it/blog/notizie/file/

To:

/it/file.php


Solution

  • You can use this code in your DOCUMENT_ROOT/.htaccess file:

    DirectorySlash On
    RewriteEngine On
    RewriteBase /
    
    ## Add a trailing slash if missing
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{THE_REQUEST} \s/+(.*?)[^/][?/]?\s
    RewriteRule [^/]$ %{REQUEST_URI}/ [L,NE,R=301]
    
    RewriteRule ^/?([a-z]{2})/.*?([^/.]+)/$ $1/$2.php [L,NC]