How do I rewrite a name to an id? - .htaccess

I'm trying to rewrite the following URL
www.domain.com/category.php?id=13
to:
www.domain.com/category/cat-name
I've followed some .htaccess tutorials but I couldn't. How can I make it work?

You cannot rewrite a number to a name, unless you have some way of translating that number to a name. This means that on the http deamon level (Apache/.htaccess) you don't have enough information to redirect it. For redirects in php, see this.
Since you ask about rewrites in php, I'll answer that too. There is no such thing as rewriting in a php file. An internal rewrite maps one url (e.g. www.domain.com/category/cat-name) and lets the server execute a different url (e.g. www.domain.com/category.php?id=13). This happens on the http deamon level, in your case Apache.
First make a .htaccess in your www-root:
RewriteEngine on
RewriteRule ^category/[^/]+$ /category.php
In category.php:
if( strpos( $_SERVER['REQUEST_URI'], 'category.php' ) != FALSE ) {
//Non-seo url, let's redirect them
$name = getSeoNameForId( $_GET['id'] );
if( $name ) {
header( "Location: http://www.domain.com/category/$name" );
exit();
} else {
//Invalid or non-existing id?
die( "Bad request" );
}
}
$uri = explode( '/', $_SERVER['REQUEST_URI'] );
if( count( $uri ) > 1 ) {
$name = $uri[1];
} else {
//Requested as http://www.domain.com/category ?
die( "Bad request" );
}
This will redirect requests to category/name if you request category.php?id=number and get the name from the url if you request category/name

Related

Can htaccess override CodeIgniter's routes.php

I'm wondering if it's possible to override routes.php rules with htaccess in Codeigniter 3.
For example, in order to point dynamic subdomains to the same controllers and pass the subdomain as a parameter, routes.php falls short for doing this, while in htaccess is really simple to do.
Another example is to mask query strings with URL segments. Routes.php doesn't allow to use query strings, but htaccess is, again, perfect for this.
So, as a general question, is it possible to use htaccess for all routing in CodeIgniter instead of using routes.php?
I think you can use htaccess for static routing in codeigniter. But for dynamic routing application base like http://localhost/myproject/user/1
you have to use routes.php.
Codeigniter routes config is used to route module/controller/method/variable patterns.
I think, domain/subdomains go out from this config, however you could use dinamic base_url, based on $_SERVER variables, and then get the string (subdomain) from the specific controller.
From my config, on CI 2.x
$config['base_url'] = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ? 'https' : 'http';
$config['base_url'] .= '://'. $_SERVER['HTTP_HOST'];
$config['base_url'] .= isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != '80' && $_SERVER['SERVER_PORT'] != '443' ? ( ':'.$_SERVER['SERVER_PORT'] ) : '';
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
then do something like this...
$server = $_SERVER['HTTP_HOST'];
$domain = preg_replace('#^www\.(.+\.)#i', '$1', $server);
$domain = $this->extract_domain($domain);
$subdomain = $this->extract_subdomains($server);
function extract_domain($domain)
{
if(preg_match("/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i", $domain, $matches))
{
return $matches['domain'];
} else {
return $domain;
}
}
function extract_subdomains($domain)
{
$subdomains = $domain;
$domain = $this->extract_domain($subdomains);
$subdomains = rtrim(strstr($subdomains, $domain, true), '.');
return $subdomains;
}

Better URL formatting with Custom Post Types and Taxonomies

I'm using Toolset Types and wondering how easy it is to set up the URL's how I want.
I have a custom post type of venues and I have a custom category taxonomy of location.
Currently the urls are coming out like
http://domain.com/venue/location/manchester/
http://domain.com/venue/manchester/the-venue-name/
But I want the URL's to be structured like
http://domain.com/manchester/
http://domain.com/manchester/the-venue-name/
Where do I need to look to make these changes?
Is this all .htaccess work or can something be done within the permalinks section?
Thanks in advance
If i understand right, this hack must work in your template.
First of all we have to remove the Post type name from url Slug.
function ft_remove_postType_slug_fromUrl( $post_link, $post, $leavename ) {
if ( 'venue' != $post->post_type || 'publish' != $post->post_status ) {
return $post_link;
}
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
return $post_link;
}
add_filter( 'post_type_link', 'ft_remove_postType_slug_fromUrl', 10, 3 );
But this is not gonna work by itself. If u pate this code in your functions.php u should get 404 Error.Bbecause WordPress only expects posts and pages to behave this way.
So, you have to add this action also.
function ft_change_parsingRequest( $query ) {
if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
return;
}
if ( ! empty( $query->query['name'] ) ) {
$query->set( 'post_type', array( 'post', 'venue', 'page' ) );
}
}
add_action( 'pre_get_posts', 'ft_change_parsingRequest' );
After this, you renew / refresh yours post type / permalink tree (It calls flush_rewrites i guess.), It means, re-update your permalink settings on your admin panel area.
Or if you want to see or do some magic, you can check it out from source url.
https://core.trac.wordpress.org/browser/tags/4.3/src/wp-includes/post.php#L1454
This Line says;
add_permastruct( $post_type, "{$args->rewrite['slug']}/%$post_type%", $permastruct_args );
Happy Coding.

Htaccess redirect different urls to redirect

I am writing some redirects because we're updating a website but we got to some trouble.
Here are some examples urls to redirect:
www.website.nl/location/depul.html -> www.website.nl/poppodium-de-pul
www.website.de/location/depul.html -> www.website.de/de_pul
www.website.nl/location/naturereserve.html -> www.website.nl/natuurgebied
www.website.de/location/naturereserve.html -> www.website.de/naturschutzgebiet
The different languages have different urls. So i have to redirect the .de url to the page on .de and the .nl url to the page on .nl
I was trying to use Redirect 301 but it seems impossible to use a full url in the to be redirected url.
Redirect 301 www.website.nl/location/depul.html www.website.nl/poppodium-de-pul
Does anyone know what i can do?
Thanks
Solved using php in my index.
Here is my code if anyone is interested.
$redirect_urls = array(
'/home.html' => array('','','',''),
'/hotelthing.html' => array('hotel','hotel','lhotel','hotel'),
'/hotelrooms/singleroom.html' => array('rooms/eenpersoonskamer','rooms/einzelzimmer','rooms/chambre_simple','rooms/single_room'),
'/hotelrooms/doubleroom.html' => array('rooms/tweepersoonskamer','rooms/doppelzimmer','rooms/chambre_double','rooms/double_room')
);
if (isset($redirect_urls[$_SERVER['REQUEST_URI']])){
$tld = strrchr ( $_SERVER['SERVER_NAME'], "." );
$tld = substr ( $tld, 1 );
if ($tld == 'nl') $sub = 0;
if ($tld == 'de') $sub = 1;
if ($tld == 'fr') $sub = 2;
if ($tld == 'com') $sub = 3;
header('Location: http://' . $_SERVER['SERVER_NAME'] . '/' . $redirect_urls[$_SERVER['REQUEST_URI']][$sub], true, 301);
exit();
}
Use this method:
Redirect 301 /location/depul.html www.website.nl/poppodium-de-pul

how to change http:mydomainname.com/inner-page.php?articleid=10 To http:mydomainname.com/inner-page.php/Title

how to change http:mydomainname.com/inner-page.php?articleid=10 To http:mydomainname.com/inner-page.php?articleid=Title
please give me a easy way i have also tried Apache mod_rewrite.
but my confusion is that how to .htaccess file know my title by id
You cannot do this with mod_rewrite or Apache alone, because there is no way Apache or mod_rewrite know how to translate from "10" to "Title". You'll most likely want to do this with a database lookup, and you are better off doing this in your inner-page.php.
if( isset( $_GET['articleid'] ) ) {
$title = database_lookup_function( $_GET['articleid'] );
header( '302 Moved Temporarily' );
header( "location: /inner-page.php?articletitle=$title" );
exit();
}
Or if you really want to keep the same variable thorough your entire script, which sounds silly:
if( isset( $_GET['articleid'] ) && intval( $_GET['articleid'], 10 ) == $_GET['articleid'] ) {
$title = database_lookup_function( $_GET['articleid'] );
header( '302 Moved Temporarily' );
header( "location: /inner-page.php?articleid=$title" );
exit();
}
To load inner-page.php?category=radiono&lanug=India&articleid=sarukh-khan-performs-a-na‌​tural-language when inner-page.php/radiono/India/sarukh-khan-performs-a-natural-language is requested, use the following rule:
RewriteRule ^inner-page\.php/([^/]+)/([^/]+)/([^/]+)/?$ /inner-page.php?category=$1&lanug=$2&articleid=$3 [L]

Magento: Browser detection to load right language

How do I implement a browser detection into Magento to load the right language.
Example:
If a US User is surfing to my Magento shop, Magento should load the path: ..myshop../usa/
usa=storecode
If a japanese User is surfing to my Magento shop, Magento should load the path: ..myshop../jp/
jp=storecode
and so on
I guess I have to adapt the .htaccess with rewrite Urls, but I never did that before. How do I have to do it?
How does the code of browser detection look like and where do I have to put it? In the header.phtml?
thank you very very much in advance!
Edit:
index.php in CE 1.7.0.2 looks like this
/**
* Error reporting
*/
error_reporting(E_ALL | E_STRICT);
/**
* Compilation includes configuration file
*/
define('MAGENTO_ROOT', getcwd());
$compilerConfig = MAGENTO_ROOT . '/includes/config.php';
if (file_exists($compilerConfig)) {
include $compilerConfig;
}
$mageFilename = MAGENTO_ROOT . '/app/Mage.php';
$maintenanceFile = 'maintenance.flag';
if (!file_exists($mageFilename)) {
if (is_dir('downloader')) {
header("Location: downloader");
} else {
echo $mageFilename." was not found";
}
exit;
}
if (file_exists($maintenanceFile)) {
include_once dirname(__FILE__) . '/errors/503.php';
exit;
}
require_once $mageFilename;
#Varien_Profiler::enable();
if (isset($_SERVER['MAGE_IS_DEVELOPER_MODE'])) {
Mage::setIsDeveloperMode(true);
}
#ini_set('display_errors', 1);
umask(0);
/* Store or website code */
$mageRunCode = isset($_SERVER['MAGE_RUN_CODE']) ? $_SERVER['MAGE_RUN_CODE'] : '';
/* Run store or run website */
$mageRunType = isset($_SERVER['MAGE_RUN_TYPE']) ? $_SERVER['MAGE_RUN_TYPE'] : 'store';
Mage::run($mageRunCode, $mageRunType);
But this Link describes the follwing code which you cannot simply replace:
require_once 'app/Mage.php';
/* Determine correct language store based on browser */
function getStoreForLanguage()
{
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
foreach (explode(",", strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE'])) as $accept) {
if (preg_match("!([a-z-]+)(;q=([0-9.]+))?!", trim($accept), $found)) {
$langs[] = $found[1];
$quality[] = (isset($found[3]) ? (float) $found[3] : 1.0);
}
}
// Order the codes by quality
array_multisort($quality, SORT_NUMERIC, SORT_DESC, $langs);
// get list of stores and use the store code for the key
$stores = Mage::app()->getStores(false, true);
// iterate through languages found in the accept-language header
foreach ($langs as $lang) {
$lang = substr($lang,0,2);
if (isset($stores[$lang]) && $stores[$lang]->getIsActive()) return $stores[$lang];
}
}
return Mage::app()->getStore();
}
/* Auto redirect to language store view if request is for root */
if ($_SERVER['REQUEST_URI'] === '/') {
header('Location: '.getStoreForLanguage()->getBaseUrl());
exit;
}
#Varien_Profiler::enable();
#Mage::setIsDeveloperMode(true);
#ini_set('display_errors', 1);
umask(0);
Mage::run();
Can anybody help me to find out where to put it or where to adapt the index.php
Thank you again!
The request the browser sends has a field called "Accept-Language" header. It's formatting isn't so intuitive and if you wanted to do it correctly, is beyond the ability of the htaccess file and mod_rewrite to parse properly. Here's a typical "Accept-Language" request header:
Accept-Language: da, en-gb;q=0.8, en;q=0.7
Which means: "I prefer Danish, but will accept British English and other types of English"
So you can't simply look for the first two letters of the field. If you don't have Danish, then you've got to continue parsing to find the right language. Magento probably has some ways of dealing with this, for example: http://www.magentocommerce.com/wiki/multi-store_set_up/how_to_automatically_redirect_to_a_store_view_based_on_the_browser_language
Just paste the following code after require_once $mageFilename; in your CE 1.7.0.2 index.php:
/* Determine correct language store based on browser */
function getStoreForLanguage()
{
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
foreach (explode(",", strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE'])) as $accept) {
if (preg_match("!([a-z-]+)(;q=([0-9.]+))?!", trim($accept), $found)) {
$langs[] = $found[1];
$quality[] = (isset($found[3]) ? (float) $found[3] : 1.0);
}
}
// Order the codes by quality
array_multisort($quality, SORT_NUMERIC, SORT_DESC, $langs);
// get list of stores and use the store code for the key
$stores = Mage::app()->getStores(false, true);
// iterate through languages found in the accept-language header
foreach ($langs as $lang) {
$lang = substr($lang,0,2);
if (isset($stores[$lang]) && $stores[$lang]->getIsActive()) return $stores[$lang];
}
}
return Mage::app()->getStore();
}
/* Auto redirect to language store view if request is for root */
if ($_SERVER['REQUEST_URI'] === '/') {
header('Location: '.getStoreForLanguage()->getBaseUrl());
exit;
}
Make sure you don't delete or overwrite any code in your index.php file and you should be fine!

Resources