Home » Php » php – how to generate seo friendly URL in codeigniter with passing blog id and blog title?

php – how to generate seo friendly URL in codeigniter with passing blog id and blog title?

Posted by: admin February 25, 2020 Leave a comment

Questions:

Hello all i am using codeigniter and i was wondering how do i create a better url for my blogs
like right now i am having

CURRENT URL

domain.com/article?seo=On-Page-Optimization-Off-Page-Optimization&id=6

DESIRED URL

domain.com/article/On-Page-Optimization-Off-Page-Optimization/6

My routes.php file is like this

$route['default_controller'] = 'main';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['sitemap\.xml'] = "Sitemap/index";
$route['(:any)'] = "main/$1";
$route['admin'] = 'admin/login';

My Htaccess file is like this

RewriteEngine On
# remove /index.php/main/ from URLs
RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{THE_REQUEST} \s/+index\.php/main/ [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^index\.php/main(/.*)?$ https://%1$1 [L,NC,NE,R=301]

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^ index.php [L]
    Header set Access-Control-Allow-Origin "*"
</IfModule>

# remove index.php
RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{THE_REQUEST} /index\.php [NC]
RewriteCond %{REQUEST_URI} ^(.*/)index\.php$ [NC]
RewriteRule ^ %1 [L,R=301,NE]

# remove main
RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{THE_REQUEST} /main [NC]
RewriteCond %{REQUEST_URI} ^(.*/)main$ [NC]
RewriteRule ^ %1 [L,R=301,NE]

# To externally redirect /dir/file.php to /dir/file
RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{THE_REQUEST} \s/+(.+?)\.php[\s?] [NC]
RewriteRule ^ /%1 [R=301,NE,L]

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

Header set Access-Control-Allow-Origin "*"

RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L,QSA] 

Here you may see that i am removing my index.php and controller name (main.php) by using the htaccess and routes.php file.

Please note:

  • Controller name is Main.php (Always)
  • Function Name is article

when i call the function by link like this

<a href="<?=base_url('index.php/main/article')?>?seo=article-name&id=123"> See Article </a>

i access the article in the article function by using GET like $id=$_GET['id'] and then get all the data from database.

hope you geot my problem and can help me find a solution for this issue.

i am sure i can pass parameters etc but i have no idea. plz help

How to&Answers: