2

I was trying to shorten the URL more, but I was removing .php file extension from the URLs using URL rewriting too. I can't run both at the same time.

Removing the extensions and trying to shorten link from

example.com/profile.php?id={username}

to

example.com/username

.htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.php [NC]
RewriteRule ^([a-zA-Z0-9-z]+)$ profile.php?id=$1 [NC]

Just the first thing I'm trying to do works, or removing extension, or removing profile.php?id, not both.

2

Because your rules conflict...

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

Your first rule matches a request of the form /username and rewrites this to username.php, before your second rule gets a chance to see the request. username.php does not match your second rule.

One way to avoid this conflict, in this instance, is to first check that the request + .php maps to a valid file before trying to rewrite to it. (Assuming username.php is not a valid file.)

For example:

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

You can probably remove the first two conditions that check that the request does not map to a file (since your regex omits the dot) or directory (unless you have file basenames that share the same name with a directory).

The NC (nocase) flag is not necessary in either of the rules you posted. And there is no need to escape a literal dot when used inside a character class.

However, this URL structure is inherently ambiguous, since you can't have a username that exists as a file in the document root (maybe that's not an issue for you).

RewriteRule ^([a-zA-Z0-9-z]+)$ profile.php?id=$1 [NC]

The trailing z in the character class looks like an error (maybe even -z unless you allow hyphenated usernames)?

Again, the NC flag is not required here, since you are already checking both lower and uppercase letters in the RewriteRule pattern.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.