skip to Main Content

I am a beginner and I have just hosted my first ever website; the problem I am faced with now is how to make my site visitors access pages on my site even without adding the page extension.

Example: www.example.com/services Instead of www.example.com/services.php

3

Answers


  1. You can use url rewrite to append the extension when one is not specified. OR you could build a routing system to link specific uri to a specific resource (quick example here). The latter introduces a lot of complexity but gives much more control. For example, here is basic pseudo code based on a custom routing system I built:

    $routes->addStaticRoute(
        /* Pattern */ '/home/myPage',
        /* Params  */ null,
        /* File    */ 'path/to/myPage.php'
    );
    

    All requests automatically go to index.php where my router translates the url request into an actual routes to a resource. With the above static route, if a user requests http://mySite/home/myPage, the router will respond with the static file at path wwwroot/path/to/myPage.php.

    Another example of a static route:

    $routes->addStaticRoute(
        /* Pattern */ '/home/{fileName}.{extension}',
        /* Params  */ ['fileName' => 'index', 'extension' => 'php'],
        /* File    */ 'path/to/{fileName}.{extension}'
    );
    

    If a user requests http://mySite/home the router will respond with the default wwwroot/path/to/index.php. Further, if they request http://mySite/home/page5, router will respond with (if exists) wwwroot/path/to/page5.php.

    Routing is somewhat of an advanced concept and these are some oversimplified examples but I hope this gets you started.

    Login or Signup to reply.
  2. edit .htaccess file and add the following

    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^(.*)$ $1.php
    

    and it will be done

    Login or Signup to reply.
  3. This is the usual solution:

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule .* $0.php [L]
    

    But if you want to use $_SERVER['PATH_INFO']) to allow:

    http://my.domain/script/a/b
    # instead of 
    http://my.domain/script.php/a/b
    

    … you need something like:

    # specifix scripts:
    RewriteRule ^(script1|script2)/(.*) /$1.php/$2 [L]
    # or more general, but with issues for sub-directotries
    RewriteRule ^([^./]+)/(.*) $1.php/$2 [L]
    
    # final rules:
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule .* $0.php [L]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search