Creating SEO friendly urls using htaccess

2019-01-26 00:03发布

问题:

I am trying to rewrite the urls of a site, i should mention that the way index.php works now is getting the p (page) parameter and including the appropriate file.

So requesting a page is like this:

www.domain.com/index.php?p=home
www.domain.com/index.php?p=search
www.domain.com/index.php?p=profile
www.domain.com/index.php?p=contact

I found how to create a rewrite rule for this:

RewriteRule ^([A-Za-z0-9-]+)/?$ index.php?p=$1

so now www.domain.com/home would give me the home page

But i also need to have a friendly url for this

www.domain.com/index.php?p=profile&id=20

to

www.domain.com/profile/20/profile-friendly-name

or better

www.domain.com/profile/profile-friendly-name

*The profile-friendly-name refers to a company name

Requirements:

  1. To have friendly urls for all pages e.g. /home, /contact

  2. To have a particular friendly url for the profile page with the profile name in the url

My questions:

  1. How can i add a profile-friendly-name to the url with the existing url format (index.php?p=profile&id=20)?

  2. Can i only have a unique name there (without the id), like my last example?

  3. If i manage to do that, will i have to change ALL the existing urls within the site (links, urls to images, to files) to the friendly format?

  4. I noticed that after applying the first RewriteRule some css stylesheets and js are not included. What is wrong?

回答1:

RewriteRule ^profile/([0-9]+)/([A-Za-z0-9-]+)/?$ index.php?p=profile&id=$1

Should work for :

www.domain.com/index.php?p=profile&id=20

to

www.domain.com/profile/20/profile-friendly-name


回答2:

Ex 1 : https://example.com/books.php?bookName=php using htaccess url will be written like this https://example.com/php

You can do this using code given below in .htaccess file:

RewriteEngine On
RewriteRule ^([^/\.]+)/?$ books.php?bookName=$1

Ex 2 :

https://example.com/books.php?bookName=php&&chapter=array using htaccess url will be written like https://example.com/php/array

You can get by using code in .htaccess file given below:

RewriteEngine On
RewriteRule ^([^/\.]+)/([^/\.]+)?$ books.php?bookName=$1&chapter=$2