Apache2 [SOLVED]: Some Pages without .php extension Mod Rewrite

Apache2 [SOLVED]: Some Pages without .php extension Mod Rewrite

Home Forums Apache2 Apache2 [SOLVED]: Some Pages without .php extension Mod Rewrite

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
  • #36519



    So I have this site, It has a directory structure like this:

    1. index.php
    2. page1.php
    3. page3.php
    4. folder/index.php
    5. example/index.php
    6. page4.php

    I want to remove the .php file extension only from the URLs that are not in a subdirectory. Because If I remove the .php from all the URLS like so:

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^.]+)$ $1.php [NC,L] 

    The files in subdirectories like which were previously accessible by this URL: https://example.com/folder now give a 404 unless I enter index.php or file name at the end of it.

    So I want to know the following:

    • How can I remove .php from only a select few targeted files so that the files in a folder/subdirectory are not affected?
    • How can I change the above .htaccess code so that it does not target the files that are in a folder/subdirectory?



    Accepted AnswerAnswer

    If you want to add .php extension to only files in site root then use:

    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^([^/.]+)/?$ $1.php [L]

    Here negated character class [^/.]+ will match only file in current directory as it matches 1 or more characters that are not / and .

    However if you want to correctly add .php to all files then use this rule:

    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^(.+?)/?$ $1.php [L]

    Source: https://stackoverflow.com/questions/47947162/some-pages-without-php-extension-mod-rewrite
    Author: anubhava
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.