didsun
didsun

Reputation: 111

PHP rewrite URL htaccess multiple conditions

I'm trying to rewrite URL addresses but I have not made much progress. I read a lot and tried, but I did not manage to do what I want. I would be glad if someone gave an idea how it could be. What I want to do is:

  1. Remove ".php" extension, for ex. "site.com/about"
  2. If i type "site.com/index.php" or "site.com/index" to redirect to "site.com"
  3. If i type "site.com/profile.php?profile=alex" to rewrite URL to "site.com/profile/alex"

Also keep the path of the files that I'm include such as css, js, images or php.

What I have tried separately:

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

2. RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /index.php?/$1 [L]

3. RewriteEngine On RewriteRule ^profile/(.+)[/]?$ profile.php?profile=$1

Upvotes: 1

Views: 347

Answers (1)

anubhava
anubhava

Reputation: 784898

You can have these rules in site root .htaccess:

Options -MultiViews
RewriteEngine On

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} \s/+profile\.php\?profile=([^\s&]+)\s [NC]
RewriteRule ^ /%1? [R=302,L,NE]

# To externally redirect /dir/file.php to /dir/file
RewriteCond %{THE_REQUEST} \s/+(.*?/)?(?:index|(\S+?))\.php[\s?] [NC]
RewriteRule ^ /%1%2 [R=301,L,NE]

# To internally forward /dir/file to /dir/file.php
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

# internal forward from pretty URL to actual one
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ profile.php?profile=$1 [L,QSA]

Upvotes: 1

Related Questions