How rewrite url in php?

If you only want to change the route for picture.php then adding rewrite rule in .htaccess will serve your needs, but, if you want the URL rewriting as in Wordpress then PHP is the way. Here is simple example to begin with.

Folder structure

There are two files that are needed in the root folder, .htaccess and index.php, and it would be good to place the rest of the .php files in separate folder, like inc/.

root/
  inc/
  .htaccess
  index.php

.htaccess

RewriteEngine On
RewriteRule ^inc/.*$ index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]

This file has four directives:

  1. RewriteEngine - enable the rewriting engine
  2. RewriteRule - deny access to all files in inc/ folder, redirect any call to that folder to index.php
  3. RewriteCond - allow direct access to all other files ( like images, css or scripts )
  4. RewriteRule - redirect anything else to index.php

index.php

Because everything is now redirected to index.php, there will be determined if the url is correct, all parameters are present, and if the type of parameters are correct.

To test the url we need to have a set of rules, and the best tool for that is a regular expression. By using regular expressions we will kill two flies with one blow. Url, to pass this test must have all the required parameters that are tested on allowed characters. Here are some examples of rules.

$rules = array( 
    'picture'   => "/picture/(?'text'[^/]+)/(?'id'\d+)",    // '/picture/some-text/51'
    'album'     => "/album/(?'album'[\w\-]+)",              // '/album/album-slug'
    'category'  => "/category/(?'category'[\w\-]+)",        // '/category/category-slug'
    'page'      => "/page/(?'page'about|contact)",          // '/page/about', '/page/contact'
    'post'      => "/(?'post'[\w\-]+)",                     // '/post-slug'
    'home'      => "/"                                      // '/'
);

Next is to prepare the request uri.

$uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' );
$uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' );
$uri = urldecode( $uri );

Now that we have the request uri, the final step is to test uri on regular expression rules.

foreach ( $rules as $action => $rule ) {
    if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) {
        /* now you know the action and parameters so you can 
         * include appropriate template file ( or proceed in some other way )
         */
    }
}

Successful match will, since we use named subpatterns in regex, fill the $params array almost the same as PHP fills the $_GET array. However, when using a dynamic url, $_GET array is populated without any checks of the parameters.

    /picture/some+text/51

    Array
    (
        [0] => /picture/some text/51
        [text] => some text
        [1] => some text
        [id] => 51
        [2] => 51
    )

    picture.php?text=some+text&id=51

    Array
    (
        [text] => some text
        [id] => 51
    )

These few lines of code and a basic knowing of regular expressions is enough to start building a solid routing system.

Complete source

define( 'INCLUDE_DIR', dirname( __FILE__ ) . '/inc/' );

$rules = array( 
    'picture'   => "/picture/(?'text'[^/]+)/(?'id'\d+)",    // '/picture/some-text/51'
    'album'     => "/album/(?'album'[\w\-]+)",              // '/album/album-slug'
    'category'  => "/category/(?'category'[\w\-]+)",        // '/category/category-slug'
    'page'      => "/page/(?'page'about|contact)",          // '/page/about', '/page/contact'
    'post'      => "/(?'post'[\w\-]+)",                     // '/post-slug'
    'home'      => "/"                                      // '/'
);

$uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' );
$uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' );
$uri = urldecode( $uri );

foreach ( $rules as $action => $rule ) {
    if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) {
        /* now you know the action and parameters so you can 
         * include appropriate template file ( or proceed in some other way )
         */
        include( INCLUDE_DIR . $action . '.php' );

        // exit to avoid the 404 message 
        exit();
    }
}

// nothing is found so handle the 404 error
include( INCLUDE_DIR . '404.php' );

Simple redirection

  • Edit the .htaccess file:

RewriteEngine On
RewriteRule .* testing.php

This code redirects each request to the testing.php script.

  • or:

RewriteEngine On
RewriteRule letstest /test_wslash/testing.php

This code redirects each /letstest request to the /test_wslash/testing.php script.

  • This restricts website access to www.example.com, which is good for SEO:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule ^(.*) http://www.example.com/$1 [QSA,L,R=301]

Redirect to a particular folder without displaying the folder in question

  • If your website is not in the target folder, this will force all requests to use www.example.com, when in reality the page is called: ww.example.com/MySite

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com
RewriteCond %{REQUEST_URI} !^/MySite
RewriteRule ^(.*)$ /MySite/

URL rewriting

mod_rewrite enables URL rewriting

  • .htaccess :

RewriteEngine On
RewriteCond %{REQUEST_URI} !testing.php
RewriteRule (.*) testing.php?var=$1

These rules run the testing.php script with the GET variable containing the URL.

  • php:


print("testing server 
\n"); print("var: {$_GET['var']}\n"); ?>

Automatically redirect visitors to SSL when they visit the unsecured version of the website

The mod_rewrite module enables you to rewrite URLs.

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

Go further

Join our community of users on https://community.ovh.com/en/.


Did you find this guide useful?

Please feel free to give any suggestions in order to improve this documentation.

Whether your feedback is about images, content, or structure, please share it, so that we can improve it together.

Your support requests will not be processed via this form. To do this, please use the "Create a ticket" form.

Thank you. Your feedback has been received.


These guides might also interest you...

How rewrite URL in PHP with example?

Here is simple example to begin with..
Folder structure. There are two files that are needed in the root folder, . ... .
.htaccess RewriteEngine On RewriteRule ^inc/.*$ index.php RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.php [QSA,L] ... .
index.php. ... .
Complete source define( 'INCLUDE_DIR', dirname( __FILE__ ) . '/.

How do you rewrite a URL?

Creating a rewrite rule.
Go to IIS Manager..
Select Default Web Site..
In the Feature View click URL Rewrite..
In the Actions pane on the right-hand side, click Add rules….
In the Add Rules dialog box, select Blank Rule and click OK..

How rewrite URL in PHP without htaccess?

As other people said, just use links like /index. php/nice/looking/url . Else, you could ask your hoster to redirect any URL to /index. php so that you can handle URL rewriting without having /index..
Better use $_SERVER['PATH_INFO'] instead of $_SERVER['REQUEST_URI'] in this case. ... .
This workaround looks good..

What is URL rewriting explain with example?

Url rewriting is a process of appending or modifying any url structure while loading a page. The request made by client is always a new request and the server can not identify whether the current request is send by a new client or the previous same client.