Ok guys i have maybe a stupid problem, but i'm probably dumb :)
I have this simple .htaccess:
Options +FollowSymlinks
RewriteEngine on
RewriteBase /
RewriteRule ^news/([^/]+)$ news-inside.php?n=$1 [L]
RewriteRule ^news/?$ news.php [L]
RewriteCond %{REQUEST_FILENAME} !-f
Every time i try to get into first rule by typing some urls like these:
http://host/news/something
i get redirected to the file news.php, not to news-inside.php with the query string!
looking at the $_GET and $_SERVER of the reached page, this is the result:
$_GET => empty
$_SERVER (some)
'REQUEST_METHOD' => string 'GET' (length=3)
'QUERY_STRING' => string '' (length=0)
'REQUEST_URI' => string '/news/something' (length=15)
'SCRIPT_NAME' => string '/news.php' (length=9)
'PATH_INFO' => string '/something' (length=10)
'PATH_TRANSLATED' => string '/var/www/rolo/something' (length=23)
'PHP_SELF' => string '/news.php/something' (length=19)
Any ideas??
Try to disable MultiViews:
Options -MultiViews
Related
I have a URL that looks like:
url.com/picture.php?id=51
How would I go about converting that URL to:
picture.php/Some-text-goes-here/51
I think WordPress does the same.
How do I go about making friendly URLs in PHP?
You can essentially do this 2 ways:
The .htaccess route with mod_rewrite
Add a file called .htaccess in your root folder, and add something like this:
RewriteEngine on
RewriteRule ^/?Some-text-goes-here/([0-9]+)$ /picture.php?id=$1
This will tell Apache to enable mod_rewrite for this folder, and if it gets asked a URL matching the regular expression it rewrites it internally to what you want, without the end user seeing it. Easy, but inflexible, so if you need more power:
The PHP route
Put the following in your .htaccess instead: (note the leading slash)
FallbackResource /index.php
This will tell it to run your index.php for all files it cannot normally find in your site. In there you can then for example:
$path = ltrim($_SERVER['REQUEST_URI'], '/'); // Trim leading slash(es)
$elements = explode('/', $path); // Split path on slashes
if(empty($elements[0])) { // No path elements means home
ShowHomepage();
} else switch(array_shift($elements)) // Pop off first item and switch
{
case 'Some-text-goes-here':
ShowPicture($elements); // passes rest of parameters to internal function
break;
case 'more':
...
default:
header('HTTP/1.1 404 Not Found');
Show404Error();
}
This is how big sites and CMS-systems do it, because it allows far more flexibility in parsing URLs, config and database dependent URLs etc. For sporadic usage the hardcoded rewrite rules in .htaccess will do fine though.
If you only want to change the route for picture.php then adding rewrite rule in .htaccess will serve your needs, but, if you want the URL rewriting as in Wordpress then PHP is the way. Here is simple example to begin with.
Folder structure
There are two files that are needed in the root folder, .htaccess and index.php, and it would be good to place the rest of the .php files in separate folder, like inc/.
root/
inc/
.htaccess
index.php
.htaccess
RewriteEngine On
RewriteRule ^inc/.*$ index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]
This file has four directives:
RewriteEngine - enable the rewriting engine
RewriteRule - deny access to all files in inc/ folder, redirect any call to that folder to index.php
RewriteCond - allow direct access to all other files ( like images, css or scripts )
RewriteRule - redirect anything else to index.php
index.php
Because everything is now redirected to index.php, there will be determined if the url is correct, all parameters are present, and if the type of parameters are correct.
To test the url we need to have a set of rules, and the best tool for that is a regular expression. By using regular expressions we will kill two flies with one blow. Url, to pass this test must have all the required parameters that are tested on allowed characters. Here are some examples of rules.
$rules = array(
'picture' => "/picture/(?'text'[^/]+)/(?'id'\d+)", // '/picture/some-text/51'
'album' => "/album/(?'album'[\w\-]+)", // '/album/album-slug'
'category' => "/category/(?'category'[\w\-]+)", // '/category/category-slug'
'page' => "/page/(?'page'about|contact)", // '/page/about', '/page/contact'
'post' => "/(?'post'[\w\-]+)", // '/post-slug'
'home' => "/" // '/'
);
Next is to prepare the request uri.
$uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' );
$uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' );
$uri = urldecode( $uri );
Now that we have the request uri, the final step is to test uri on regular expression rules.
foreach ( $rules as $action => $rule ) {
if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) {
/* now you know the action and parameters so you can
* include appropriate template file ( or proceed in some other way )
*/
}
}
Successful match will, since we use named subpatterns in regex, fill the $params array almost the same as PHP fills the $_GET array. However, when using a dynamic url, $_GET array is populated without any checks of the parameters.
/picture/some+text/51
Array
(
[0] => /picture/some text/51
[text] => some text
[1] => some text
[id] => 51
[2] => 51
)
picture.php?text=some+text&id=51
Array
(
[text] => some text
[id] => 51
)
These few lines of code and a basic knowing of regular expressions is enough to start building a solid routing system.
Complete source
define( 'INCLUDE_DIR', dirname( __FILE__ ) . '/inc/' );
$rules = array(
'picture' => "/picture/(?'text'[^/]+)/(?'id'\d+)", // '/picture/some-text/51'
'album' => "/album/(?'album'[\w\-]+)", // '/album/album-slug'
'category' => "/category/(?'category'[\w\-]+)", // '/category/category-slug'
'page' => "/page/(?'page'about|contact)", // '/page/about', '/page/contact'
'post' => "/(?'post'[\w\-]+)", // '/post-slug'
'home' => "/" // '/'
);
$uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' );
$uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' );
$uri = urldecode( $uri );
foreach ( $rules as $action => $rule ) {
if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) {
/* now you know the action and parameters so you can
* include appropriate template file ( or proceed in some other way )
*/
include( INCLUDE_DIR . $action . '.php' );
// exit to avoid the 404 message
exit();
}
}
// nothing is found so handle the 404 error
include( INCLUDE_DIR . '404.php' );
this is an .htaccess file that forward almost all to index.php
# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_URI} !-l
RewriteCond %{REQUEST_FILENAME} !\.(ico|css|png|jpg|gif|js)$ [NC]
# otherwise forward it to index.php
RewriteRule . index.php
then is up to you parse $_SERVER["REQUEST_URI"] and route to picture.php or whatever
PHP is not what you are looking for, check out mod_rewrite
Although already answered, and author's intent is to create a front controller type app but I am posting literal rule for problem asked. if someone having the problem for same.
RewriteEngine On
RewriteRule ^([^/]+)/([^/]+)/([\d]+)$ $1?id=$3 [L]
Above should work for url picture.php/Some-text-goes-here/51. without using a index.php as a redirect app.
For example, i use this code for testing routes:
$app->get('/api', function () {
echo 'get!';
});
$app->post('/api', function () {
echo 'post!';
});
$app->put('/api', function () {
echo 'put!';
});
For api testing i use RestClient plugin for Chrome.
When i try do GET request, response is 'get!'. Its good.
But:
When i try do POST request, response also is 'get!'. Why? Its must be 'post!'.
When i try do PUT request, (in Response Headers: Allow: GET,HEAD,POST,OPTIONS,TRACE ) Slim response have 405 error (Method Not Allowed) with message:
"The requested method PUT is not allowed for the URL /api."
What am I doing wrong?
Be sure that your .htaccess is the following (from slimphp/Slim#2.x):
RewriteEngine On
# Some hosts may require you to use the `RewriteBase` directive.
# If you need to use the `RewriteBase` directive, it should be the
# absolute physical path to the directory that contains this htaccess file.
#
# RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
I have designed a web application, It works for two different users say user1 and user2, and both of the users need the view in different languages.
I have studied about yii:t() but by that method we have to define language in main.config, which set the same language for both users.
How can I translate my view in different languages for both users?
I hope this can help you:
you need to edit urlmanager.php in your components, if there is no file, you need to create one.
Check this url: Multilingual
Thanks.
Put this in your SiteController.php:
public function actionChangeLocale($locale) {
// (OPTIONAL) if is registered user (not guest), save preferred locale in database
if (!Yii::app()->user->isGuest) {
// Update user settings
$uid = Yii::app()->user->id;
User::model()->updateByPk($uid, array('locale' => $locale));
}
// change locale
Yii::app()->user->setState('_locale', $locale);
// redirect to previous page, in the new locale
if(isset($_SERVER["HTTP_REFERER"]))
$referrer = $_SERVER["HTTP_REFERER"];
else
$referrer = Yii::app()->getBaseUrl(true) . '/';
$this->redirect($referrer);
}
Edit your main.php config url manager rules:
'urlManager' => array(
'urlFormat' => 'path',
'showScriptName' => false,
'caseSensitive' => false,
'rules' => array(
'lang/<id:\w+>' => 'site/changeLocale',
To change locale, create a link to point user to desired locale:
http://www.mysite.com/myapp/lang/en
http://www.mysite.com/myapp/lang/zh
http://www.mysite.com/myapp/lang/ja
http://www.mysite.com/myapp/lang/in
...
If you saved the logged-in user's preferred locale in database, add this to SiteController.php Login action:
$uid = Yii::app()->user->id;
$user = User::model()->findbypk($uid);
$userLocale = isset($user->locale) ? $model->locale : Yii::app()->language;
Yii::app()->user->setState('_locale', $userLocale);
Above usage is for those using htaccess rewrite. Make sure base .htaccess file is:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L] # Remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
Related Articles:
http://www.yiiframework.com/doc/guide/1.1/en/topics.i18n
Related Modules:
http://www.yiiframework.com/extension/ei18n/
UPD:
Solved. The problem was because we're using nginx as a frontend. So nginx doesn't pass the HTTP_HOST to apache.
Hi there!
I'm having a problem with getting subdomain parameter in my base controller on a production server while on the localhost it's ok. other parameters from url like controller, action returned as they should.
this returns null on production:
$agencyName = (string) $this->_getParam('agency');
no changes made to .htaccess:
RewriteEngine On
RewriteRule ^main - [L,NC]
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
and here's my vhost settings:
<VirtualHost *:8080>
ServerName agencies.domain.com
ServerAlias *.agencies.domain.com
ErrorLog /var/log/apache2/agencies.domain_errors.log
DocumentRoot /var/www/agencies.domain.com/public/
<Directory "/var/www/agencies.domain.com/public">
Options -Indexes FollowSymLinks Includes
DirectoryIndex index.shtml index.php
AllowOverride All
# Controls who can get stuff from this server.
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
Does anybody knows why it happenes?
upd:
routers in Bootstrap
public function run()
{
$frontController = Zend_Controller_Front::getInstance();
$router = $frontController->getRouter();
$plainPathRoute = new Zend_Controller_Router_Route(
':module/:controller/:action/*',
array(
'module' => 'default',
'controller' => 'index',
'action' => 'index',
)
);
$config = $this->getOptions();
$hostnameRoute = new Zend_Controller_Router_Route_Hostname(
':agency.' . $config['siteUri'],
NULL,
array(
'agency' => '([a-z0-9]+)'
)
);
$router->addRoute('subdomain', $hostnameRoute->chain($plainPathRoute));
parent::run();
}
and yes, I do have $config['siteUri'] defined and i also tried using :agency.domain.com getting the same problem again
Use the following :
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initRoute()
{
$this->bootstrap('FrontController');
$router = $this->getResource('FrontController')->getRouter();
$router->removeDefaultRoutes();
$plainPathRoute = new Zend_Controller_Router_Route(
':module/:controller/:action/*',
array(
'module' => 'default',
'controller' => 'index',
'action' => 'index',
)
);
$router->addRoute('default', $plainPathRoute);
$config = $this->getOptions();
$hostnameRoute = new Zend_Controller_Router_Route_Hostname(
':agency.' . $config['siteUri'],
NULL,
array(
'agency' => '([a-z0-9]+)'
)
);
$router->addRoute('subdomain', $hostnameRoute->chain($plainPathRoute));
}
}
If you provide a valid subdomain (ie. only consisting of characters a-z0-9), it will be passed in agency, if not then agency will not be set. (At least it works for me using ZF 1.11.3 :p).
Solved. The problem was because we're using nginx as a frontend. So nginx doesn't pass the HTTP_HOST to apache.
this is my controller in CI
class Welcome extends Controller {
function Welcome()
{
parent::Controller();
}
function index()
{
}
function bil($model='')
{ }
I want to do a rewrite so that
http://example.com/index.php/welcome/bil/model
becomes
http://example.com/model
in my htaccess I have
RewriteBase /
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/welcome/$1 [L]
#RewriteRule ^(.*)$ /index.php/welcome/bil/$1 [L]
I thought it should be as easy as removing the /index.php/welcome/ part
but when I uncomment the last line it get 500 internal server error
You'll want to use mod_rewrite to remove your index.php file like you have above, but use CodeIgniter's routing features to reroute example.com/model to example.com/welcome/bil/model.
In your routes.php configuration file, you can then define a new route like this:
// a URL with anything after example.com
// will get remapped to the "welcome" class and the "bil" function,
// passing the match as a variable
$route['(:any)'] = "welcome/bil/$1";
So then, typing example.com/abc123 would be equivalent to example.com/welcome/bil/abc123.
Note that only characters permitted by $config['permitted_uri_chars'] (which is located in your config.php file) are allowed in a URL.
Hope that helps!