2

I have a small PHP MVC framework which runs on a droplet that uses Ubuntu and I'm trying to make all the URLs 'friendly'. From:

index.php?u=controller/method/param

To:

controller/method/param

For that I'm using a .htaccess file containing this code:

Options -MultiViews
RewriteEngine on

RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) index.php?u=$1 [L,QSA]

With this I can make the URL friendly, but the unfriendly URL is still there. Therefore I can access the same content both ways:

index.php?u=controller/method/param

That is the same as:

controller/method/param

How do I force the URL to always be friendly? No more index.php?u=?

Eliah Kagan
  • 116,445
  • 54
  • 318
  • 493
emma
  • 177
  • 6
  • 3
    Reviewers: I see no reason to consider this off-topic. In particular, this isn't a question about how to write PHP code. `.htaccess` files are used to configure the Apache web server. – Eliah Kagan Jul 19 '19 at 20:14
  • @EliahKagan will there be a problem if i repost this question? Two days passed by and i'm still stuck #-o – emma Jul 20 '19 at 20:51
  • 1
    Please *don't* post intentional self-duplicates. You can instead **[edit]** your question, *if* you have information to add or improvements to make. This bumps it to the front page, which I think is your goal. But you should only edit to make useful changes. Usually people edit too little, but it is possible to edit excessively. The system alerts moderators if very many edits are made in a short time. Anyway, I just edited your question, which has the same positive effects on visibility as your own edits (though that's not why I did it). See also https://askubuntu.com/help/no-one-answers. – Eliah Kagan Jul 20 '19 at 22:46
  • @EliahKagan, oky, thank you! – emma Jul 21 '19 at 07:58
  • I just thought to ask: do you want the unfriendly URLs to always redirect immediately to the friendly ones? Or do you want the unfriendly URLs to actually be invalid, giving a 404 error? I'm guessing you want the former, but I'm not sure. I recommend that you **[edit]** your question to provide clarification about this. – Eliah Kagan Jul 23 '19 at 04:54

1 Answers1

1

Use the below rule, we are redirecting any request to index.php which has u query param to newly created pretty url.

Options -MultiViews
RewriteEngine on

RewriteBase /
RewriteCond %{REQUEST_URI} ^index.php$
RewriteCond %{QUERY_STRING} ^u=(.*)$
RewriteRule ^ http://example.com/%1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*)$ index.php?u=$1 [L,QSA]