apache.htaccessmod-rewrite

I want to rewrite my url for single mobile page using .htaccess


Gadgets92
    - mobiles
        - index.php
        - product.php
        - .htaccess

I have above folder structure

Also, I have registered Gadgets92 folder as gadgets92.test using Windows virtual host

In my http://gadgets92.test/mobiles/index.php file I have link to product.php file as "http://gadgets92.test/mobiles/slug".

I want to convert "http://gadgets92.test/mobiles/slug" to "http://gadgets92.test/mobiles/product.php?slug=slug" using .htaccess

I have tried

RewriteEngine On

# Rewrite rule for "/mobiles/slug" to "/mobiles/product.php?slug=slug"
RewriteRule ^mobiles/([^/]+)$ /mobiles/product.php?slug=$1 [L]


Solution

  • I put the .htaccess file to the root directory (Gadgets92) and write the following code in it.

    RewriteEngine On
    
    # Exclude "index.php" and "action.php" from rewriting in each directory
    RewriteCond %{REQUEST_URI} !^/(mobiles|laptops|watches|televisions|headsets)/index\.php$
    RewriteCond %{REQUEST_URI} !^/(mobiles|laptops|watches|televisions|headsets)/action\.php$
    
    RewriteRule ^(mobiles|laptops|watches|televisions|headsets)/([^/]+)/?$ $1/product.php?slug=$2 [QSA,L]
    

    Now it accepts slugs write it as product.php?slug=slug internally. It does not rewrite other files in those folders except for product.php.