Response
stringlengths
8
2k
Instruction
stringlengths
18
2k
Prompt
stringlengths
14
160
I would suggest usingModernizrfor this.It uses Javascript on the client browser to detect support for a whole range of browser features, including touch events, and gives you CSS classes and a Javascript object which you can use to adjust your site to suit the user's browser.I would always avoid doing browser detection on the server (ie in .htaccess or in your server-side code), because it's unreliable -- the data which the server can use to detect the client environment is sent as plain text and is easily spoofed or hacked. More importantly, it's also commonly suppressed by proxies and privacy apps.
Ok so I've been researching this for a while and seems there are a few ways to do this, CSS media queries that detect the screen size, htaccess and javascript.I would prefer to go the htaccess route, because as far as I know, tablets now have 1024px resolution. Wouldn't this interfere with desktop resolutions? Also htaccess gives me the opportunity to make a whole new site for tablets and mobile browsers, but how do I go about detecting whether it's a tablet or a mobile? I don't want to have to detect if it's a Google Nexus vs an HTC Desire or iPhone, up against iPad, Acer Iconia, Xoom, etc.Is there a way to detect a tablet, phone or desktop computer, without having to include every single make and model? (for example as here.)
Detecting tablets and phones, htaccess or CSS
I think you just need to add a couple more conditions to exclude them.RewriteCond %{REQUEST_URI} !^/clients/ RewriteCond %{REQUEST_URI} !^/somefolder/And have these in front of your Rewrite rule in the subfolder section. That will stop it embedding/website/into the URI if it already contains/clients/or/somefolder/
I'm being stuck setting up my htaccess properly. Currently I have the following situation and file structure in my htdocs folder:.htaccess/website/clients/blabla/somefolderAs you might guess, the folder "website" contains all the files that should be accessible upon navigation tohttp://mydomain.com- this works fine with the current htaccess:RewriteEngine on # remove www RewriteCond %{HTTP_HOST} ^www.mydomain.com$ [NC] RewriteRule ^(.*)$ http://mydomain.com/$1 [R=301,L] # subfolder RewriteCond %{HTTP_HOST} ^mydomain.com$ [OR] RewriteCond %{HTTP_HOST} ^www\.mydomain\.com$ RewriteCond %{REQUEST_URI} !^/website/ RewriteRule (.*) /website/$1 # clean urls RewriteRule ^website/([a-z0-9\-]+)$ website/$1.phpMy problem: While I want my website to be accessible the way it is now I also want to be able to accesshttp://mydomain.com/clients/blalaandhttp://mydomain.com/somefolderetc... With my current htaccess this results in a 404 Error saying "The requested URL /website/clients/blabla was not found on this server."What do I need to add / change to my htaccess to make this work?Thanks in advance
htaccess: multiple sub folders and website access
Have you considered just using unset Last-Modified?Example:<IfModule mod_headers.c> <FilesMatch "\.(json|pdf|swf|bmp|gif|jpeg|jpg|png|svg|tiff|ico|flv|js)$"> Header unset Last-Modified </FilesMatch> </IfModule>The FilesMatch section looks fine, so it's probably just some fiddly bit with Header Set. Hell, might even be case sensitive. TryHeader setinstead ofHeader SetIf this isn't what you want, then let me know and I'll think about it a bit more. Unset should work though,
I'm tyring to implement browser caching and follow Google PageSpeed's recommendation about setting Last-Modified to a data that is "sufficiently far enough in the past." I have the following in my .htaccess:<IfModule mod_headers.c> <FilesMatch "\.(json|pdf|swf|bmp|gif|jpeg|jpg|png|svg|tiff|ico|flv|js)$"> Header Set Last-Modified "Fri, 01 Jan 2010 12:00:00 GMT" </FilesMatch> </IfModule>I have mod_headers installed on my server.Unfortunately, Google PageSpeed still complains and warns me:Leverage browser caching The following cacheable resources have a short freshness lifetime. Specify an expiration at least one week in the future for the following resources:And then lists PNGs, GIFs, JPGs, etc. Yahoo YSlow says basically the same thing.Looking at the response headers of one of my resources that should be caching, I see this:Date: Tue, 19 Oct 2010 20:12:04 GMT Server: Apache/2.2.14 (Ubuntu) Last-Modified: Tue, 07 Sep 2010 23:51:33 GMT Etag: "2e0e34-2a43-48fb413a96a20" Accept-Ranges: bytes Content-Length: 10819 Content-Type: image/pngAs you can see, the Last-Modified data does not match what I specified in .htaccess.Any ideas what I am doing wrong?
Last-Modified not working for .htaccess
Finally the solution was as simple as that...# password-protect single file <Files my_controller> AuthName "my_controller" AuthType Basic AuthUserFile /home2/afolder/.htpasswds/.htpasswd require valid-user </Files>just removed .php and everything is fine...
Hello there I want to password protect one of my controllers in codeigniter. This is the code in .htaccess# password-protect single file <Files my_controller.php> AuthName "my_controller.php" AuthType Basic AuthUserFile /home2/afolder/.htpasswds/.htpasswd require valid-user </Files>the problem is that myController.php will show up in my url as/my_controller/(no .php) so the protection has no effect...can I do something to overcome this problem? thanks in advance
.htpasswd in codeigniter
If you don't want Apache to display the list of files in the directory, you can useOptions -IndexesTo disable theindexesfeature.See theOptions Directivesection of Apache's manual, for more informations.Else, an "easy way" would be to just put an emptyindex.htmlorindex.phpfile -- i.e. a default file that Apache uses when one is trying to access a directory.About that, see theDirectoryIndex Directive.
I'm building a website, but I'm not entirely sure what to do with the .htaccess file. Say for example I have a folder called pages which holds all my pages, can i deny access to someone if they type in www.website.com/pages so that they can't see the directory? I've tried putting the .htaccess file in the pages folder with the "deny from all" line and although it denies access, it's also denying access to the actual pages. Is there a way to do this without denying access to see the pages on the website, just denying access to the directory?Sorry if this doesn't make much sense, I'm so confused lol. Thanks for any help.
.htaccess file. Can I block access to a directory without blocking access to the files within it?
I think you may have meant this for your regex:RewriteCond %{REQUEST_URI} !(^exported/?|\.(php|gif|jpe?g|png|css|js|pdf|doc|xml|ico)$) RewriteRule (.*)$ /url.php [L]Doeshtml/exported/exported/work in your current setup by any chance?
I have 2 directories each with a .htaccess file:html/.htaccess - There is a rewrite in this file to send almost everything to url.phpRewriteCond %{REQUEST_URI} !(exported/?|\.(php|gif|jpe?g|png|css|js|pdf|doc|xml|ico))$ RewriteRule (.*)$ /url.php [L]and html/exported/.htaccessAuthType Basic AuthName "exported" AuthUserFile "/home/siteuser/.htpasswd" require valid-userIf I remove html/exported/.htaccess the rewriting works fine and the exported directory can be access. If I remove html/.htaccess the authentication works fine.However when I have both .htaccess files exported/ is being rewritten to /url.php. Any ideas how I can prevent it?
htaccess rewrite and auth conflict
The ? at the end of a destination (destinations are not regular expressions) means to go to that destination with no query string.RewriteCond %{QUERY_STRING} ^id=(.*)$ RewriteRule ^oldpage\.php$ http://new-site.com/newpage-%1 [R=301,L]If the query string contains only an id, it stores the value which is then used in the destination, so if you havehttp://foo.com/oldpage.php?id=54you'll end up withhttp://new-site.com/newpage-54?id=54If you haveRewriteCond %{QUERY_STRING} ^id=(.*)$ RewriteRule ^oldpage\.php$ http://new-site.com/newpage-%1? [R=301,L]You'll go to the same destination but with an empty query string, so going tohttp://foo.com/oldpage.php?id=54will end up inhttp://new-site.com/newpage-54
RewriteCond %{QUERY_STRING} ^id=(.*)$ RewriteRule ^oldpage\.php$ http://new-site.com/newpage-%1 [R=301,L] and RewriteRule ^oldpage\.php$ http://new-site.com/newpage-%1? [R=301,L]In first case result isnew-site.com/newpage-3?id=3in secondnew-site.com/newpage-3What does question mark in second rewrite rule means?
Question mark in the end of RewriteRule
Instead of providing a link to an image. Provide a link to a cgi script which will automatically provide the proper header and content of the image.For example: image.php?sample.jpgYou can then make sure they are already authenticated (e.g. pass a session id) as part of the link.This would be part of the header, and then your image data can follow.header('Content-Type: image/jpeg');Edit: If it has to be fast, you can write this in C/C++ instead of php.
I'm putting together a portfolio website which includes a number of images, some of which I don't want to be viewable by the general public. I imagine that I'll email someone a user name and password, with which they can "log-in" to view my work.I've seen various solutions to the "hide-an-image" problem on line including the following, which uses php's readfile. I've also seen another that uses .htaccess.Use php's readfile() or redirect to display a image file?I'm not crazy about the readfile solution, as it seems slow to load the images, and I'd like to be able to use Cabel Sasser's FancyZoom, which needs unfettered access to the image, (his library wants a link to the full sized image), so that rules out .htaccess.To recap what I'm trying to do:1) Provide a site where I give users the ability to authenticate themselves as someone I'd like looking at my images. 2) Restrict random web users from being able see those images. 3) Use FancyZoom to blow up thumbnails.I don't care what technology this ends up using -- Javascript, PHP, etc. -- whatever's cleanest and easiest.By the way, I'm a Java Developer, not a web developer, so I'm probably not thinking about the problem correctly.
Restricting access to images on a website
+100You can get mod_rewrite to generate amap from external sourcesuch as executing a PHP or Python file which can get the data from the database and create a mod_rewrite map.http://httpd.apache.org/docs/2.0/misc/rewriteguide.html(See right at the bottom)For exampleRewriteMap quux-map prg:/path/to/map.quux.plGood Luck
Im developing a new site, and I'd like to store my rewrite rules in a database, instead of right in the .htaccess files.I have another site that uses Opensef (http://sourceforge.net/projects/opensef/) with a Joomla! installation that is doing this, but im not even 100% how it works underneath the hood.How can I store these rules in a database, query for them on request and rediret to the clean URL if found? Is there a better way to do this instead of loading up a .htaccess file (there may be 1000's of entries)?Thank you,
How can I store my Rewrite Rules in a database?
I think you'll have to do it in two bits... Take out $2, precede every capital (apart from the first) with a -, then use just append the result tohttp://www.foo.com/mountain-lifestyle/with a .aspx on the end.
I am trying to do a regex match and replace for an .htaccess file but I can't quite figure out the replace bit. I think I have the match part right, but maybe someone can help.I have this url-http://www.foo.com/MountainCommunities/Lifestyles/5/VacationHomeRentals.aspxAnd I'm trying to turn it into this-http://www.foo.com/mountain-lifestyle/Vacation-Home-Rentals.aspx(MountainCommunities/Lifestyles)/\d/(.*)(.aspx)and then I figured I would have a rewrite rule starting like this-mountain-lifestyle/$2$3but I need to take what is in $2 in this instance and rewrite it to place dashes between the words with capital letters. Now I'm stumped.
RegEx match replace help
For Godaddy, my solution was, after updating the php to add the following line (Taking the old php declaration out):AddHandler application/x-httpd-alt-php74___lsphp .php .html .htmIt really just required the explicit declaring of the page type.
Currently using "AddHandler application/x-httpd-ea-php56 .php" in my htaccess file in the root of the domain since that is the only thing that works.If I try to switch to php7, the page either tries to download or it gets the HTTP ERROR 500.The following downloads the page:AddHandler application/x-httpd-ea-php7 .phpThe following gives me 500 error:AddHandler application/x-httpd-ea-php71 .phpDownloads the page:AddHandler x-httpd-php7 .php500 error:<IfModule mime_module> AddType application/x-httpd-ea-php72 .php .php7 .phtml .htm .html </IfModule>500 error:<IfModule mime_module> AddHandler application/x-httpd-ea-php73 .php .php7 .phtml </IfModule>downloads the page:AddHandler application/x-httpd-php7 .php .html .htm .phtml .shtmletcIn subdirectories, I can use the following just fine:<IfModule mime_module> AddHandler application/x-httpd-ea-php73 .php .php7 .phtml </IfModule>Try to use that in the root .htaccess file...poof no cookie.If I add AddHandler application/x-httpd-ea-php56 .php back in, it works fine again.I have also tried other some other methods I found searching around. Has anyone else had this issue? The host is Bluehost.The only other things semi-related that I have in the root htaccess file is the following, but I have tried removing it as well with no change to the results:AddHandler server-parsed .html AddHandler server-parsed .htm
AddType in htaccess causes either download or HTTP ERROR 500
Using 2 Redirect URLs in this particular order solved it.Redirect 301 /post1 https://www.website2.com/post1 Redirect 301 /post1/ https://www.website2.com/post1
I have to manually redirect few URLs in my website1 to website2.Below is my code in the.htaccessfile of website1Redirect 301 /post1/ https://www.website2.com/post1When I enterhttps://www.website1.com/post1/in the browser it's being redirected tohttps://www.website2.com/post1successfully, as expected.But, When I enterhttps://www.website1.com/post1in the browser it's being redirected tohttps://www.website2.compost1, the slash is missing afterhttps://www.website2.comWhat could be done to solve this?
301 redirection not redirecting to the right URL without a trailing slash
Unrecognized Content-Security-Policy directive 'frame-ancestors'This is a browser-level error, you can't fix this. Are you using Safari 9 or older? Safari only supportsframe-ancestorsstarting inSafari 10. The error also simply means the browser is ignoring what is, to it, an invalid directive it has no idea what to do with. It shouldn't negatively impact your site beyond what would normally occur if that directive weren't there. Not all console errors need to be acted on.When using stuff like Content Security Policy, some older browsers are simply not going to support all features. You should still implement them due to the concept of progressive enhancement.Note that Safari is frankly basically the new IE in terms of lagging behind support for standards, especially older versions. Don't expect bleeding edge support, but don't feel afraid to implement new features because of it. Unlike IE safari does catch up, and these missing features don't entirely break websites like they used to. It's not just Safari either, Firefox gets things before Chrome sometimes etc.
I have an application siteA.com that is loaded in an iframe inside siteB.com. No warning loading directly siteA.com but gettingUnrecognized Content-Security-Policy directive 'frame-ancestors'when is inside an iframe in siteB.com; this only in Safari.All these changes were made in siteA.comMeta Tagwith no luck<meta http-equiv="Content-Security-Policy" content="frame-ancestors siteB.com">What headers should I add to siteA.com to allow Content-Security-Policy directive frame-ancestors?Then I tried in the mainindex.phpadding in the head:header("Content-Security-Policy: frame-ancestors 'self' siteB.com;");but still is working in siteA but not siteB.Also added to* .htaccess *Header set Content-Security-Policy "frame-ancestors: siteB.com"but nothing. Since the problem is rising in Safari, tried also withheader("X-Frame-Options: ALLOW-FROM siteB.com");but this even gives an error.The nice part is that it doesn't load at all in any of the other tested browsers if the frame-ancestors url is not the correct one.What am I doing wrong?
Safari: Unrecognized Content-Security-Policy directive 'frame-ancestors'
Try this:return $this->redirect($url, 301);
I have an entityEventwith parametersidandslugin my Symfony app. Parameterslugis nullable and not required so, if it missing, link to the single event page builds usingid. But, ifslugis set, url is build using this parameter.The task is to create 301 redirect for the events which are have slug. I'm, trying to use symfony methodredirect()but I encountered a problem: when I set slug for the first time, it works fine and replaced me from the urlevent/3toevent/my-event-slug. But when I removing slug or change it browser are still redirecting my to my first slug which was provided.I'm checking it in Chrome console and it shows to me that my redirect 301 was loaded from cache.How can I prevent saving redirect to the cache or how can I solve this problem in another way in controller?
Symfony 301 redirect in the controller
Just put this.htaccessfile in the folder you want to protect:AuthUserFile /var/www/site/.htpasswd AuthName "Admin Access" AuthType Basic require valid-userFromhttps://httpd.apache.org/docs/2.4/howto/auth.htmlFor example, if you wish to protect the directory /usr/local/apache/htdocs/secret, you can use the following directives, either placed in the file /usr/local/apache/htdocs/secret/.htaccess, or placed in httpd.conf inside a <Directory "/usr/local/apache/htdocs/secret"> section.But with the newIfdirective we could do it from the root directory as well:<If "'%{REQUEST_URI}' =~ m#/?admin(/.*)?#"> AuthUserFile /var/www/site/.htpasswd AuthName "Admin Access" AuthType Basic require valid-user </If>I tested this positive on a Ubuntu 16.04.03 LTS Server with Apache 2.4.27.
I have the following config in my.htaccessfile, which is working in Apache 2.2, but not in 2.4:SetEnvIf Request_URI ^/admin require_auth=true AuthUserFile /var/www/site.htpasswd AuthName "Admin Access" AuthType Basic Require all denied Satisfy any Require valid-user Allow from env=!require_authHow do I convert this to work in Apache 2.4? Basically, if the URI starts with/admin, then they should be asked for the password.
Require valid user in Apache 2.2 to 2.4
To redirect just the root, you can use the followingRedirectMatch 301 ^/$ http://example2.com/
I want to redirect just the root of my site www.example.com to www.example2.com but not the subfolders www.example.com/subfolder ! Is it possible?E.G. the following rule redirect all my site:Redirect 301 / http://www.example2.com
Redirect root but not subfolders
Into folder members create new folder files, move here all your songs, create new .htaccess file and add the following lines:Order Deny,Allow Deny from allInto folder members create file get_file.php and add the following code:if( !empty( $_GET['name'] ) ) { // check if user is logged if( is_logged() ) { $file_name = preg_replace( '#[^-\w]#', '', $_GET['name'] ); $question_file = "{$_SERVER['DOCUMENT_ROOT']}/files/questions/{$file_name}.zip"; if( file_exists( $question_file ) ) { header( 'Cache-Control: public' ); header( 'Content-Description: File Transfer' ); header( "Content-Disposition: attachment; filename={$question_file}" ); header( 'Content-Type: application/zip' ); header( 'Content-Transfer-Encoding: binary' ); readfile( $question_file ); exit; } } } die( "ERROR: invalid song or you don't have permissions to download it." );URL to get the file: localhost/get_file.php?name=file_name
My website contains some download content. I want to access download this file only for logged in user.If user type direct file url in browser it show forbidden page if user not logged in. Am not using any CMS. Direct File Link: localhost/files/questions/20160917070900-w2CdE9LZpE.zipI searched on net but failed to find any good answer. Please suggest me how can I do it.
How to block direct download file
-fcheck requires full filesystem path. You can do this using%{DOCUMENT_ROOT}variable:RewriteEngine on RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{QUERY_STRING} ^$ RewriteCond %{DOCUMENT_ROOT}/post/$1.php -f RewriteRule ^(.+)$ post/$1.php [L]
I would like the URL:http://domain.com/category/subcategory/titleTo point to:http://domain.com/posts/category/subcategory/title.phpMy .htaccess file looks like this:RewriteEngine on RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{QUERY_STRING} !^.+ #RewriteCond post/%{REQUEST_URI}.php -f RewriteRule ^(.*)$ post/$1.php [L]This works however when I uncomment the line above it does not work.I have tried:RewriteCond /post/%{REQUEST_URI}.php -f RewriteCond post/%{REQUEST_URI}.php -f RewriteCond post%{REQUEST_URI}.php -fNone of these work. What am I doing wrong?Also is there an easy way to debug these rules? Like console logging variables or something?
Using RewriteCond with %{REQUEST_URI} for mod_rewrite
Found one solution.By default New Wamp disable the Fancy directory listings.Edit the C:\wamp64\bin\apache\apache2.4.17\conf\httpd.confNeed to load this module (remove the #)LoadModule autoindex_module modules/mod_autoindex.soNeed to load this conf (remove the #)Include conf/extra/httpd-autoindex.confReference links:WAMP is not displaying the icons in the directory listingThanks
I am usingwamp server 3in my local machine. Whenever I make a virtual host I have to provide at least oneindex.phpfile to access my project directory, without it I am getting an404error.But I also want to access my project directory without providing theindexfile. I like to see the directory lists when server doesn't find an index file. Like the below image:I think the issue is in myhttpd-vhost.conffile. Here is the virtual-host configuration of the directory that I want to enable directory listing:<VirtualHost *:80> ServerName virtualhost.info DocumentRoot c:/wamp64/www/virtual_host_test <Directory "c:/wamp64/www/virtual_host_test/"> Options Indexes FollowSymLinks MultiViews AllowOverride All Require local </Directory> </VirtualHost>Any help would be greatly appreciated.
How to enable directory listing in a virtual host of WAMP Server 3
Which version of flup do you use ? It seems they released a new dev version on 10.12.2015 which is downloaded as the latest stable version and is python3 only. For me downgrading toflup==1.0.3.dev-20110405fixed the problem
I'm deploying a Django project followingthis stepsmy .htaccess is:AddHandler fcgid-script .fcgi RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ mysite.fcgi/$1 [QSA,L]my .fcgi:#!/homeX/your_username/python27/bin/python27 import sys, os # Add a custom Python path. sys.path.insert(0, "/homeX/your_username/python27") sys.path.insert(13, "/homeX/your_username/myproject") os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings' from django.core.servers.fastcgi import runfastcgi runfastcgi(method="threaded", daemonize="false")When I runpython2.7 mysite.fcgito prove it is working, it throws me:Can't import flup.server.fcgiHow can I importflup.server.fcgi?I'm using:Django 1.8.7,flup 1.0.3,python 2.7,psycopg2forpostgreSQL, and all was download usingpip.
Can't import flup.server.fcgi
Try this rule at top of your .htaccess:RewriteEngine on RewriteCond %{THE_REQUEST} \.pdf[?\s] [NC] RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost [NC] RewriteRule ^ - [F]
I wrote a small download script to hide the file path, the file "get_file.php" handles everything. next step I would like to disallow with htaccess all pdf-files from direct access trough the browser (if anybody knows the exact url to the file), but still provide access to the file with my "get_file.php".I tried:RewriteEngine on RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost [NC] RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost.*$ [NC] RewriteRule \.(pdf)$ - [F]any ideas?
htaccess: disallow all pdf files but allow from php script (file download script)
You can use this rule in site root .htaccess:RewriteEngine On # block everything except /folder/public/ RewriteRule !^folder/public/ - [F,NC]
I have this structure:/folder/public/ /folder/text.txt /folder/app/ (etc...)I want visitors to access to /public/ except everything else.
.htaccess - How to deny all directories except one?
I attempted to do a comment but it's too much. You can do this if you own both domains. If you don't have hosting on the first domain but you do on theother domain, then you can add the main domain as anServerAliason the other server.Either through your control panel or your vhost config do the following.Add an A record forblog.domain.comin DNS pointing to the IP address of the other domain with the hosting account.In the configuration of the web server with the hosting add aServerAliasofblog.domain.comto theanotherdomain.comvhost config.in the root of theanotherdomain.comput this code inside your .htaccess file.If you want it to actually redirect then you can do thisRewriteEngine on RewriteCond %{HTTP_HOST} ^blog\.domain\.com [NC] RewriteRule ^(.*)$ http://anotherdomain.com/blog/$1 [R=301,L]If you don't want it to redirect and keep blog.domain.com in the address bar then, you can do this.RewriteEngine on RewriteCond %{HTTP_HOST} ^blog\.domain\.com [NC] RewriteRule ^(.*)$ /blog/$1 [L]
I'm trying to redirect one subdomain (a wordpress.com domain) into a folder of another domain. Example:blog.domain.com to anotherdomain.com/blogI know that is possible by using .htacces files, but i dont have a hosting service on my first domain.Is it possible to do it by using DNS?I have tried by creating some A and CNAME registrations but I cant find a way to do it: Can I have a ip for a specific folder of my second domain?Thanks :)
Redirect subdomain into a folder of another domain
You can use session data to make sure users of page2 have passed through page 1With the way sessions work,Theencrypted stringis quite secure even if it is not encrypted at all.on page1:session_start(); $_SESSION['secret_key'] = 'encrypted_string';on page2:session_start(); if($_SESSION['secret_key'] == 'encrypted_string'){ // user is authorized echo 'You are authorized to see this page'; } else{ echo 'Please visit page1 before accessing this page'; } // Logic for authorized userOr, shorter version for page2 :if(empty($_SESSION['secret_key']) || $_SESSION['secret_key'] != 'encrypted_string'){ die('You are not authorized to view this page.'); } echo 'only authorized user will see from here forward';BTW, when testing, remember that once your session is set, you will have to delete sessions in browser, or use incognito to test again. To delete cache on chromectrl+shift+deleteand choose cookies and other
I am trying to have page1.php redirect to page2.php after 5 seconds. However page2.php needs to be a restricted page that can only be viewed if you are being sent from --> mydomain.com/page1.php and can not be accessible if you type the address manually into the address bar.I have tried methods that use shared keys, htaccess and php HTTP_REFERRER.I believe the issue is coming from the redirection, and I believe it is because the redirect script is not sending the HTTP_REFERRER and therefore page2.php is looking at the url sent from the redirection script as being manually entered. I have tried with a simple php redirect and javascript. Below are the two different redirect scripts I have used.php version.header( "refresh:5;url=page2.php" );Javascript version.<script type="text/javascript"> function Redirect() { window.location="page2.php"; } setTimeout('Redirect()', 5000); </script>I have tried these with the full url and with/without http:// for example mydomain.com/page2.php.Page2.php needs to only accept traffic from page1.php. I have no objection as to how to go about achieving this. Using shared keys or any other aspect just as long as the user can not enter the address manually and visit the page. I am also fully aware the Referrer can be spoofed however I do not have the expertise to get to advanced.
Redirect after 5 seconds but only allow the page to be accessed by the referrer
To redirect only home page use:RewriteCond %{HTTP_HOST} ^recherchegoldens\.com$ [NC] RewriteRule ^/?$ http://whitegoldenretriever.com/ [R=301,L]Make sure to test this in a new browser to avoid old browser cache.
I have a website that needs redirected, but I can't just redirect the / directory because there are other websites in folders on the server, and doing that redirects them as well. NOT GOOD!So I have my .htaccess file with a bunch of 301 redirects for individual HTML pages, and those work fine. But I need to redirect the home page. Here is what I have to do that:RewriteEngine on RewriteBase / RewriteCond %{HTTP_HOST} ^recherchegoldens.com [NC] RewriteRule ^(.*)$ http://whitegoldenretriever.com/$1 [R=301,L]That forwards the home page, great. But it also messes up my other 301 redirects. Here is one of my redirects:Redirect 301 /Available-Pups.html http://www.whitegoldenretriever.com/available-pups/But with the rewrite rule above, if I type in recherchgoldens.com/Available-Pups.html, it just forwards to whitegoldenretriever.com/Available-Pups.htmlBut I don't want that. I want it to still forward to the location set in my Redirect 301 directive.What am I doing wrong?
Using mod_rewrite to redirect home page ONLY
+50You have to installmod_geoipOn Debian:apt-get install libapache2-mod-geoip edit /etc/apache2/mods-available/geoip.conf <IfModule mod_geoip.c> GeoIPEnable On GeoIPDBFile /usr/share/GeoIP/GeoIP.dat </IfModule> /etc/init.d/apache2 reloadThen you can limit access to visitors except from US with the following lines:SetEnvIf GEOIP_COUNTRY_CODE US AllowedCountry Deny from all Allow from env=AllowedCountry
What is the best .htaccess configuration to allow only US users to visit a site?I can't seem to find a definitive answer that covers all IPV4 and IPV6 users.
Allow only US users to visit site
Have your/myfolder/myapp/.htaccesslike this:<IfModule mod_rewrite.c> RewriteEngine on RewriteBase /myfolder/myapp/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /index.php/$1 [L] </IfModule>then in/myfolder/myapp/application/config/config.phpyou need to have this config:$config['base_url'] = ''; $config['index_page'] = ''; $config['uri_protocol'] = 'AUTO';
I am struggling with this for hours now: I have a codeigniter application in asub folderin a godaddy hosting, lets say:mydomain.com/myfolder/myapp/I have this .htaccess:<IfModule mod_rewrite.c> RewriteEngine on RewriteBase /myfolder/myapp/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /index.php?$1 [L] </IfModule>I read this doc:https://github.com/bcit-ci/CodeIgniter/wiki/Godaddy-Installation-Tipsbut it won't help neither. Maybe because my ci app is in a subfolder?How can I hide the index.php? and make it work with friendly urls?
Codeigniter .htaccess in godaddy
this one worked for meDirectoryIndex index.php RewriteEngine on RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond $1 !^(index\.php|robots\.txt) RewriteRule ^(.*)$ index.php?/$1 [L]make sure to remove index.php from appliation/config/config.php$config['index_page'] = '';
I know there's a lot of questions and answers here but I'm really confused and I couldn't fix my problem yet. Please help!I can easily access my controller via this url:http://www.example.com/new/index.php/welcomebut I can't get it via this URL:http://www.example.com/new/welcomeI'm configuring my CodeIgniter site in a subdirectory "new" and on my server, my directory structure is:/ htdocs new/ (this is empty), htdocs(here is my directory named as "new" and new(this is the exact folder where I've my codeIgniter files. I'm confused here about "/" and "htdocs", I think this is the thing which I'm not able to handle because my domain example.com is pointing to htdocs i.e if I put index.php in htdocs, example.com will load index.php.my .htaccess file in "new" directory is :RewriteEngine On #RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule (.*) index.php/$1in config/config.php:$config['index_page'] = ''; $config['uri_protocol'] = 'AUTO';I've tried$config['uri_protocol']for "Auto", "REQUEST_URI" and "QUERY_STRING" etc.With this configuration I'm able to remove index.php in my local host but I can't fix it on server. Please help!! Thanks in advance.
CodeIgniter .htaccess remove index.php on Server
This worked:Redirect 301 /old_page.php /new_page.php
I want to do a 301 redirect fromold_page.phptonew_page.phpand keep all query strings if they exist.soold_page.phpwould redirect tonew_page.phpold_page.php?test=1would redirect tonew_page.php?test=1Here is what I have below, but it's a 404 error.RewriteEngine on RewriteRule ^old_page.php(.*) new_page.php$1 [R=301,L]
301 redirect to new page keep query string
Probably a red herring, but I presume you have the tags around your .htaccess block? eg<Limit GET POST> order allow,deny allow from all deny from 100.101.102.103 </Limit>This is how I use it on one of my sites.
I try to configure a simple block of an IP address in my .htaccess. I followed examples I found here in this forum, that seemed to work fine for other users, but do not work for me and I really don't get why.My .htaccess file is very simple:Order Allow,Deny Allow from all Deny from aaa.bbb.ccc.dddI expect that the configured IP address (aaa.bbb.ccc.ddd) will be blocked. But unfortunately it is not blocked.If I set 'Deny from all' in the third line of my .htaccess, all access is blocked as expected.So it seems the directive is read by Apache but if I set anything else but 'from all' i. e. a host name or an IP or an IP wildcard etc. no blocking happens.I appreciate any help, pointing me in the right direction.Thanks Nestor
Blocking of IP in .htaccess not working
You need to tweak your regex a bit by making trailing slash optional. Use this rule:RewriteRule ^([0-9]+)(?:/([^/]*))?/?$ ./cat.php?id=$1&title=$2 [L,NC]
Stack Overflow generates rewrite URLs,so i need to know how i can do it like Stack Overflow?http://stackoverflow.com/questions/9168364/how-to-rewrite-seo-friendly-urls-like-stackoverflow => 200 ok.(without trailing slash) http://stackoverflow.com/questions/9168364/how-to-rewrite-seo-friendly-urls-like-stackoverflow/ => 200 ok.(with trailing slash) http://stackoverflow.com/questions/9168364/ => 301 redirect. http://stackoverflow.com/questions/9168364 => 301 redirect.How i can do it with mod_rewrite ?i have something like this:RewriteRule ^([0-9]+)[/]([^/]*) ./cat.php?id=$1&title=$2 [L,NC] mydomain.com/999 => 404 not found. mydomain.com/999/ => 200 ok. mydomain.com/999/test => 200 ok. mydomain.com/999/test/test2 => 200 ok. mydomain.com/999/test/test2/test3 => 200 ok. mydomain.com/999/test/test2/test3/test4 => 200 ok.please let me know how i change RewriteRule ?
htaccess rewrite url like Stack Overflow
You don't need edit htaccess. You can do it more safely by specifying the preferred URL in Settings.If you havedomain.comand want users to be redirected towww.domain.com, then keepwww.domain.comin the settings and vice versa. Wordpress will manage the www redirection.Similarly you can manage path also, if you want users to seeexample.com/bloginstead.
I have tried to redirect a Wordpress website using .htaccess but it causes to form an infinite loop. Now there is no redirection for the blog. Still the domain url with www is automatically redirecting to non www. I have checked whole server and I am sure that there is no redirect in the server. Also tried by changing the site address and Wordpress address from dashboard but still creates infinite loop.There is nothing redirection in template because I have tried by creating a simple .html test file and still the same.Note: I don't think code is relevant here because the question is where this www to non www redirection came which I haven't given in my code or in the serverRewriteCond %{HTTP_HOST} ^example.com$ RewriteRule (.*) http://www.example.com/$1 [R=301,L]update: I just found it out. Plesk configuration files is really tricky, spreads in many places. I can see that the rewrite rule was added in under conf within the website name. I have removed this and change the site url and now everything works fine. Thank you for your support
Redirect non www to www causes infinite loop
In .htaccess:RewriteEngine on RewriteRule ^/application - [F]The[F]option instructs it to issue a403 Forbiddenresponse on all matching URLs.Or add a separate .htaccess file in/applicationcontaining just:deny from allOr in your Apache vhost definition:<Location /application> deny from all </Location>
Note: This question has been asked before several times, but the answers are really bad, totally wrong and/or do not fit the above scenario (because there are several files calledindex.php). If you like, see [1].I want to block direct access to all .php files in theapplicationfolder (see file structure image) via the .htaccess file in the root folder. There are some solutions for this on the web, but they miss one thing: They don't workif there is more than one file named index.php(which is a realistic scenario like the screenshot shows, see the file in the view/xxx/ folder):Question: How to block access to all .php files, except the index.php in the root folder ?
How to block access to all .php except index.php in root folder (via .htaccess)?
Why don't you want to make it in PHP script itself? I think I saw this for the first time in Zend framework, but now using similar approach in my projects..htaccess:RewriteEngine on RewriteRule .* index.phpindex.php$path = $_SERVER['REQUEST_URI']; $paths = explode('/', $path); // Add some logic for showing the page you need. Maybe remove domain before processingFor example you can use even arguments as array keys and add argument as value for these keys.e.g. to print paths, useecho "<pre>"; print_r ($paths); echo "</pre>";
Is it possible to do an odd and even replacement in.htaccessto replace/in a url with= &?In other words I have a link like so:page/subscriber/action/manage/sortby/idand I'm wondering if there's way to simply replace the odd numbered/with=and the even/with&?I have some urls that are very long with lots of arguments and I don't want to have to write a specific rule for each one.I'm trying to convert over a very large PHP script to nicely formatted urls and it would take weeks to find every possible url and argument combination.
Dynamically Parse URL in .htaccess
Add this above yourRewriteRule ^(.*).html$ $1.php [QSA]rule:RewriteCond %{THE_REQUEST} \ /(.+)\.php RewriteRule ^ /%1.html [L,R=301]That will redirect the browser/client to the same request but with a.htmlinstead of a.php.
Currently I'm rewriting all incoming requests for *.html to *.php in my .htaccess:RewriteEngine on RewriteCond %{HTTP_HOST} ^example\.com$ [NC] RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L] RewriteRule ^(.*).html$ $1.php [QSA] ErrorDocument 404 /404.htmlSo /something.html is rewritten to /something.php.However, /something.php is still directly accessible in the browser. Now I want it to redirect to /something.html when people are accessing it in the browser, so as to avoid 2 distinct URLs for the same page of content.Is this possible to do in my .htaccess? How? I tried R=301 but it's always a redirect loop or something. Any help would be appreciated. Thanks!
301 Redirect *.php to *.html via .htaccess?
Something like this would internally redirect any request with no path or only a trailing slash to index.html, and everything else to index.php with the path as an argument.RewriteEngine on RewriteRule ^$ index.html RewriteRule ^(.*)$ index.php?$1 [L]
I want to use .htaccess to rewrite url to my webite:If url ishttp://mydomain.comorhttp://mydomain.com/the index.html will serve the request, all other urls will go to index.phpplease help!
.htaccess rewrite / to index.html, all other to index.php
you shall simply put aAuthUserFile /dev/nullin your .htaccess. That did the trick for me.for the rest of the pain that brings the configuration of auth_mysql, you have my full comprehension :)
I got an error "AuthUserFile not specified in the configuration" in my error log file. how to fix it. Here is my .htaccess file, its located in amazon file server.## mod auth_mysql AuthBasicAuthoritative Off AuthMYSQL on AuthMySQL_Authoritative on AuthMySQL_DB dbname Auth_MySQL_Host localhost Auth_MySQL_User username Auth_MySQL_Password password AuthMySQL_Password_Table tbl_name AuthMySQL_Username_Field user_name AuthMySQL_Password_Field password AuthMySQL_Empty_Passwords off AuthMySQL_Encryption_Types SHA1Sum # Standard auth stuff AuthType Basic AuthName "restricted zone" Require valid-user
AuthUserFile not specified in the configuration error?
The%{REQUEST_URI}variable includes a leading slash, so it will NEVER be blank. You can get rid of that and just use this rule:RewriteRule ^/?$ /splash/ [L,R]If you want the URL that appears in the browser's address bar to stayhttp://www.domain.com/, then remove the,Rfrom the square brackets:[L].
I'm looking to do a.htaccessfile that let any requests pass to its original destination but redirects to a specific folder (a splash screen in this case) is no destination is specified. I'm not very well-versed with.htaccessand would appreciate some help.Example: I'm requestinghttp://www.domain.com/folder/file.php, it should go through. But if I'm requestinghttp://www.domain.com/, it should redirect tohttp://www.domain.com/splash/.What I have so far redirects correctly to/splash/, but redirectseverythingto/splash/.<IfModule mod_rewrite.c> RewriteEngine On # If the requested URI is empty... RewriteCond %{REQUEST_URI} !^$ # ...then redirect to the "splash" folder RewriteRule .* splash [L] # Otherwise rewrite the base RewriteBase / # If the request is not a folder or a file, redirects to index.php RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule>Thanks!EDIT: One important point would be to redirecthttp://www.domain.com/tohttp://www.domain.com/splash/, but allow direct access tohttp://www.domain.com/index.php.
.htaccess - When there is no requested URI
Sure thing.# Enable Rewrite Engine # ------------------------------ RewriteEngine On RewriteBase / # Redirect index.php Requests # ------------------------------ RewriteCond %{THE_REQUEST} ^[^/]*/index\.php [NC] RewriteCond %{THE_REQUEST} ^GET RewriteRule ^index\.php(.+) $1 [R=301,L] # Standard ExpressionEngine Rewrite # ------------------------------ RewriteCond $1 !\.(css|js|gif|jpe?g|png) [NC] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /index.php/$1 [L]
I've been using the below code in my .htaccess file for a while to make the EE URLs work without needing index.php in the URL. What I've found though it that I'm getting some reports from crawling tools that I'm getting duplicate content as /lorem/ipsum/ is also popping up somewhere as /index.php/lorem/ipsum/.I know that this is likely a result of a stray link referencing the index.php in the URL but I'd like to close up the gaps by forcing index.php out of the links. I've had a look around but I can't seem to find how to force it out.RewriteEngine On RewriteBase / RewriteCond $1 !\.(gif|jpe?g|png)$ [NC] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /index.php/$1 [L]
Expression Engine - Removing index.php completely
You're already part way there with your use ofRewriteCondto restrict the rewrites to requests on port 80.You donotwant to rewrite requests on port 80 for/videosand/blog, so:RewriteCond %{SERVER_PORT} 80 RewriteCond %{REQUEST_URI} !^/videos RewriteCond %{REQUEST_URI} !^/blog RewriteRule ^(.*)$ https://ourdomain.com/$1 [R,L]And you want to rewrite requests for these URLs on port (presumably) 443:RewriteCond %{SERVER_PORT} 443 RewriteRule ^/((videos|blog)/.*) http://ourdomain.com/$1 [R,L]
I have used htaccess to force all pages to re route to https using...RewriteEngine on RewriteBase / RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://ourdomain.com/$1 [R,L]Is there any way I can reverse that rule for ourdomain.com/videos && ourdomain.com/blog making sure that these pages are forced to drop the https and use http?
How can I redirect all pages to https, using .htaccess, with exceptions?
+100This should do it:RewriteEngine on RewriteBase / RewriteCond %{ENV:REDIRECT_STATUS} 200 RewriteRule ^ - [L] RewriteCond %{REQUEST_URI} ([\w]+\.[\w]+)$ [NC] RewriteCond %{DOCUMENT_ROOT}/%1 -f RewriteRule ^ /%1 [NC,L] RewriteCond %{DOCUMENT_ROOT}/subdir%{REQUEST_URI} -f RewriteRule ^ /subdir%{REQUEST_URI} [L] RewriteRule ^ /index.php [L]An update with a slight optimization.RewriteEngine on #RewriteBase / RewriteCond %{ENV:REDIRECT_STATUS} 200 RewriteRule ^ - [L] RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^[^/]+\.[^/]+$ - [NC,L] RewriteCond %{REQUEST_FILENAME} (.*/)([\w]+\.[\w]+)$ [NC] RewriteCond %1subdir/%2 -f RewriteRule ^ subdir/%2 [L] RewriteRule ^ index.php [L]The above will work with anydirectory/subdirChange log:RewriteBase commented for use of relative path.Checking for /file.ext (or whether in current directory). the below will check whether file is present in current directory.RewriteCond %{REQUEST_FILENAME} -fRewriteRule ^[^/]+\.[^/]+$ - [NC,L]RewriteCond %{DOCUMENT_ROOT}/subdir%{REQUEST_URI} -fcaptures current directory in %1 and the file.ext in %2
I need to create a following rule to place in my .htaccessFor each request i'd like to execute file/path in subfolder subdir.If the file doesn't exist there then i'd like to forward this request to index.phpLet say that .htaccess iw placed athttp://domain/folderWhen the user opens urlhttp://domain/folder/Subfolder/xxx.htmlhe should recieve file fromhttp://domain/folder/subdir/Subfolder/xxx.htmlSo these rules have to consider the fact that there are subfolders inside subdir. (Different structures of subfolders :-) And only if the path under subdir doesn't exist the request should be forwarded to index.phpPlase help :)ps This is a followup question to my previous one. It is quite different and includes the fact that there are subfolders inside subdir. ->mod_rewrite: How to search in local folder, subfolder and then redirect to index.php
mod_rewrite: Redirect request to subdir with many subfolders of different structures + redirect to index.php
Add question mark?at the end of URL to prevent existing query string to be copied to a new URL:Redirect 301 /oldpage http://www.mysite.co.uk/newsubdir/newpage?But since you are already using mod_rewrite, I would recommend utilising it for this task as well (place this rule above your other rewrite rules):RewriteRule ^oldpage$ http://www.mysite.co.uk/newsubdir/newpage? [R=301,L]
A simple 301 redirect is not working in this instance - For example:Redirect 301 /oldpage http://www.mysite.co.uk/newsubdir/newpageThe site is dynamic and the .htaccess is already renaming pages to search engine friendly URL's from URL's containing a query string.RewriteRule ^(.*)/(.*)$ index.php?page_name=$1&sub=$2 [NC,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$ RewriteRule (.*)([^/])$ http://www.mysite.co.uk/$1$2/ [R=301,L]When we are using these 301 redirects like above in the same .htaccess (at the bottom), the pages are redirecting but the query string is getting added to the end of the URL frustratingly and we have not figured out why or how to prevent it.After 301 redirect, URL is looking like:-http://www.mysite.co.uk/newsubdir/newpage/?page_name=old-page&sub=...Causing a 404 error - it's just the query string added on the end of the URL's that is breaking the redirect.Please can anyone advise on what needs to be done to fix this?Thanks
301 Redirecting from old page to new page on Apache not working
I got the solution after reading bunch of lines in Apache doc :) .Just include these lines in htaccess, Its working fine for me.BrowserMatch "MSIE 9.0" ie9 header set X-UA-Compatible "IE=EmulateIE8" env=ie9
I am not able to find and way to set some header in .htaccess file only if the browser is IE9. Pseudo code for my requirement is:if (IE 9) { header set (value) } else { header set (value) }Please suggest how I can achieve this in my .htaccess file.
How to set HTTP headers in .htaccess only for IE 9
This is calledFront Controller Pattern. There are several benefits including:making sure that all common resources for all pages are included.website resource is managed and the access can be more easily restricted (e.g. admin only)makes the web application as a complete whole package, where common things such as session, session cookie and page access control are shared.
There is a number of answer of how to do it, but I can't find a reason or a set of reasons why it's a nice thing to do.
What's the purpose or benefit to redirecting all a website access to index.php using htaccess?
) you should use an HTTP 301 redirect from the old urls to the new urls (either via .htaccess or php, it does not really matter, the .htaccess rule is propably more failsafe and faster so you should go for that)2) go to google webmaster tools -> your old domain -> site configuration -> change of address -> select your (already verified) new domain3) write all the sites which linked to your old pages and tell them to please change the link (yeah, i know that this is not going to happen, but you asked for the best way...) otherwise you will have to keep the old domain running for ever and ever and ever....about meta redirect: that's a javascript redirect and google does not recommend it. if you are looking for an in HTML solution, use the canonical taghttp://www.google.com/support/webmasters/bin/answer.py?answer=139394(don't listen to the video, it's outdated, canonical work cross domain now, too) but hey with the HTTP 301 redirect you will not need it.anyway, you will probably see a slump (minus 20% to minus 30% are quite common) of google referred for three weeks anyway, don't panic. if you did everything right you will regain the traffic after that period.
I have a website which is ranked pretty well by search engines, and I want to move this site to a new domain. Only the right label from the domain name will change (.it>.com).What's the best way to redirect the old site to the new site, if possible to have minimal impact on search engine ranks?Should I use .htaccess ?Options +FollowSymLinks RewriteEngine on RewriteRule (.*) http://newurl.com/$1 [R=301,L]Or a HTML tag in each old page to redirect it to the new page URL:<meta http-equiv="Refresh" content="5;url=http://newurl.com/newpage/" />Or PHP:Header( "HTTP/1.1 301 Moved Permanently" ); Header( "Location: http://newurl.com/newpage/" );or all of the above :)What's the difference between the 3, and what's the best way ?
How to move (redirect) a website with as little impact on SEs as possible
If you have just static keywords, I would rather use ahash mapinstead of separate rules. Because the complexity of the find operation for a hash map is O(1) in opposite to O(n) fornrules.So you could do something like this:RewriteMap arabic-keywords dbm:/path/to/file/arabic-keywords.mapThe initial keywords map is a plain text file of the format:عربية arabic.php الأغاني songs.php الفنان artist.phpThen usehttxt2dbmto turn the plain text file into a hash map:httxt2dbm -i arabic-keywords.txt -o arabic-keywords.mapAnd the use of the map:RewriteCond %{arabic-keywords:$0} .+ RewriteRule .+ %0 [L]As a hash rewrite map returns an empty string if no match was found, the condition will only be fulfilled if a match was found. But note thatRewriteMapcannot be used in the .htaccess filecontext.
We are building a website that hopefully will serve 2k-5k uniques per day. Because the website is oriented for arab speakers we configured the .htaccess file to make rewrite rules like:RewriteRule ^عربية$ arabic.php [L]Problem is we have 600 Rewrite Rules like the one above. Is this Okay with apache? or is this going to make my server real slow? does the [L] tag help?
600 + mode rewrite rules, is that okay with apache?
This will do the job in your .htaccess file:RedirectMatch 301 (.*)\.htm$ $1.php
I am trying find out how to redirect all traffic on a website from any .htm address to a .php version of the page. I am hoping it will be a .htaccess rule but I have not been able to find anything that quite fits for me yet and I am not the greatest with .htaccess.Any help greatly appreciated.
Redirect *.htm to *.php
You can do this with four rules, one for each case:RewriteRule ^([^/]+)$ search.php?q=$1 RewriteRule ^([^/]+)/([0-9]+)$ search.php?q=$2&p=$1 RewriteRule ^([^/]+)/([^/]+)$ search.php?q=$2&cat=$1&p=1 RewriteRule ^([^/]+)/([^/]+)/([0-9]+)$ search.php?q=$2&cat=$1&p=$3And with this rule in front of the other rules, any request that can be mapped onto existing files will be passed through:RewriteCond %{SCRIPT_FILENAME} !-f RewriteRule ^ - [L]Now your last issue, that externally linked resources cannot be found, is due to that you’re probably using relative URL paths likecss/style.cssor./css/style.css. These relative references are resolved from the base URL path that is the URL path of the URL of the document the references are used in. So in case/category/keywordis requested, a relative reference likecss/style.cssis resolved to/category/keyword/css/style.cssand not/css/style.css. Using the absolute URL path/css/style.cssmakes it independent from the actual base URL path
I am in a new project and I'm designing the URL structure, the thing is I want URLs look like this:/category-23/keyword/5/Where the normal page is:/search.php?q=keyword&cat=23&page=5So my question is,catandpagefields, must be optional, I mean if I go to/keywordit should be/search.php?q=keyword(page 1) and if I go to/category/keywordshould be:/search.php?q=keyword&cat=category&p=1and also if I go to/keyword/5/it must be:/search.php?q=keyword&p=5Now I have my .htaccess like this:RewriteEngine On RewriteBase / RewriteCond %{SCRIPT_FILENAME} !-f RewriteCond %{SCRIPT_FILENAME} !-d RewriteRule ^(.*)/(.*)/(.*)$ search.php?q=$2&cat=$1&page=$3 [L]I cannot make it working and the CSS / image files don't load. I'd thank a lot who could give me a solution.
How to setup optional parameters in mod_rewrite
Options -Indexes
Can you please tell me how to deny folder browsing using .htaccess file
.htaccess code to deny folder browsing
You could use theRewriteCond Directiveto check whether there is an existing file that correspond to the requested URL, and only rewrite to your CMS if there is none.Here is a simple example :RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteRule .* index.phpIf there is no existing file that correspond to the requested URL, then that request is rewritten toindex.phpYou might also want to check for symbolic links and / or directories, btw...For instance, here is apossibility that can be used when setting up a Zend Framework project:RewriteEngine On RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [NC,L] RewriteRule ^.*$ index.php [NC,L](Even though it links to ZF, it should be OK for quite many projects)
I am in the process of converting a static website into one using a cms. I have the cms installed in a sub directory of the public directory. To avoid ending up with ugly domain names (http://example.com/cms/) is there an easy way using mod_rewrite to rewritehttp://example.com/…tohttp://example.com/cms/…while ensuring that if the request wouldn't have ended in a 404, there is no redirect.An example:/ /cms/index.html /cms/file.dat /file.datIf the user requests /index.html, they should get redirected to /cms/index.html, but if they request /file.dat, theyshouldn'tget redirected to /cms/file.dat because the file existed at the requested placeEDITThanks for the answers.
Using mod_rewrite only if a 404 would have occured
I believe it's the "DirectoryIndex index.php" directive in .htaccess that will do the trick.
I have recently reinstalled MacOSX, and at some point (without realizing it) I made it so that a directory without index.html would try instead to run index.php. This has since stopped working. My localhost runs .php files fine; it just doesn't do so unless you specifically tell it to.There are lots of htaccess guides online but I can't actually find one that tells me how to solve this problem :s
Run index.php rather than listing files
You may useTHE_REQUESTinIfcondition to avoid this block getting modifiedREQUEST_URI:<If "%{THE_REQUEST} =~ m#\s/+account[/?\s]#"> Header set Cache-Control "no-cache, no-store, must-revalidate" </If>
I want to set a custom header in.htaccessif the URI contains the word/account, e.g. it should match the following URIshttp://www.example.com/account,http://www.example.com/account/address.I tried with the following code but it is not working:<If "%{REQUEST_URI} =~ /account/"> Header set Cache-Control "no-cache, no-store, must-revalidate" </If>However, when I remove the if statement, the header is being set correctly.
Set header in Apache .htaccess if URI contains a word
RewriteCondis only applicable to nextRewriteRule. You can make a separate rule to skip all files and directories on top of other rewrite rules.RewriteEngine On # skip all existing files and directories RewriteCond %{REQUEST_FILENAME} -d [OR] RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^ - [L] RewriteRule ^([^/]+)/([^/]+)/?$ browse_folder.php?username=$1&folder=$2 [L,QSA] RewriteRule ^([^/]+)/?$ browse_user.php?username=$1 [L,QSA]
I want to test if file exists for both the rules at the bottom, but it only seems to work for the first one. The second rule would wrongly match my /style.css file and display the php page instead of style.css.Isn't it supposed to test if file exists for all next rules until the[L]flag ?RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^/]+)/([^/]+)/?$ browse_folder.php?username=$1&folder=$2 RewriteRule ^([^/]+)/?$ browse_user.php?username=$1 [L]If I repeat the file_exists test before each of the two lines it works as expected.RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^/]+)/([^/]+)/?$ browse_folder.php?username=$1&folder=$2 RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^/]+)/?$ browse_user.php?username=$1 [L]
RewriteCond scope
here's how I would handle this:RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?params=$1then with whatever serverside language you're using I'll use PHP parse $_GET['param'].$params = explode('/', $_GET['params']);
I am trying to achieve that a url likeexample.com/path1to example.com/index.php?p1=path1example.com/path1/path2to example.com/index.php?p1=path1&p2=path2In my .htaccess I have:RewriteEngine OnRewriteRule ^(.*)/(.*)$ /index.php?c=$1&g=$2 [NC,L]RewriteRule ^([a-zA-Z0-9-_]+)$ /index.php?g=$1 [NC,L]It works well for the case where we have the example.com/path1/path2but for the the case example.com/path1only works if there is no dot in the url. For example, I want to example.com/mydomain.com working to example.com/index.php?g=domain.com but I am not able to make it working.Could you help me with this please?
.htaccess RewriteRule path to query string
This is a good question; while thegeneralsyntax form is explained in thelink provided in comments, it doesn't explain how to correctly apply this header in the.htaccessorhttpd.confApache files.Through trial and error I found this works:<IfModule mod_headers.c> Header set Expect-CT enforce,max-age=2592000,report-uri="https://foo.example/report" </IfModule>Note that there should not be any white space in the "data" part.Also note that theoutputdetected by such things asredbot.orgdoes not show exactly the same thing.
i want to enable Expect-Ct on my website. From searching around i creaded code on my own from searches.<IfModule mod_headers.c> Expect-CT: max-age=86400, enforce, report-uri="https://foo.example/report" </IfModule>I want to ask if this is right or not and what is report uri ? it can be any random link or something else. for example my website is testwebsite.com then report uri should be testwebsite.com/report ? and how can i check reports ?
How to enable Expect-Ct on apache using .htaccess
+50You can use:RewriteEngine on # --- BEGIN domain redirect --- RewriteCond %{THE_REQUEST} \ /+main/ RewriteRule ^main/(.*)$ http://getvene.com/$1 [L,R=301] RewriteCond %{THE_REQUEST} \ /+app/ RewriteRule ^app/(.*)$ http://app.getvene.com/$1 [L,R=301] # Secret Code redirect RewriteRule ^s/(.*) /?secret-code=$1 RewriteRule ^(main|app)/ - [L] RewriteCond %{HTTP_HOST} ^(www\.)?getvene\.com$ [NC] RewriteRule ^(.*)$ /main/$1 [L] RewriteCond %{HTTP_HOST} ^(www\.)?app\.getvene\.com$ [NC] RewriteRule ^(.*)$ /app/$1 [L] # --- END domain redirect ---
I'm trying to make the domaingetvene.comopen in the subfoldermain. This works fine. But then I needgetvene.com/s/blablato be seen as/?secret-code=blabla. The RewriteRule can be seen at the bottom. Separately, these rules work fine. But together, the secret code rule has no effect. What needs to be changed?RewriteEngine on # --- BEGIN domain redirect --- RewriteCond %{THE_REQUEST} \ /+main/ RewriteRule ^main/(.*)$ http://getvene.com/$1 [L,R=301] RewriteCond %{THE_REQUEST} \ /+app/ RewriteRule ^app/(.*)$ http://app.getvene.com/$1 [L,R=301] RewriteRule ^(main|app)/ - [L] RewriteCond %{HTTP_HOST} ^(www\.)?getvene\.com$ [NC] RewriteRule ^(.*)$ /main/$1 [L] RewriteCond %{HTTP_HOST} ^(www\.)?app\.getvene\.com$ [NC] RewriteRule ^(.*)$ /app/$1 [L] # --- END domain redirect --- # --- BEGIN Secret Code redirect --- RewriteRule ^s/(.*) /?secret-code=$1 [L] # --- END Secret Code redirect ---
.htaccess domain open from subfolder then rewriterule
Try thisChange$config['index_page'] = 'index.php/home';To$config['index_page'] = '';.htaccessRewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?$1Check Your default controller value inapplication/config/routes.php$route['default_controller'] = 'welcome';checkapplication/controllers/Welcome.php exist or nototherwise change$route['default_controller']value as your requirement
Our code are as belowapplication/config/config.php$config['base_url'] = 'http://myworldmirror.com/'; $config['index_page'] = 'index.php/home';.htaccessRewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L] Options -Indexesapplication/config/database.php$active_group = 'default'; $query_builder = TRUE; $db['default'] = array( 'dsn' => '', 'hostname' => 'localhost', 'username' => 'newsels1', 'password' => 'newsels1', 'database' => 'newsels1', 'dbdriver' => 'mysql', 'dbprefix' => '', 'pconnect' => FALSE, 'db_debug' => (ENVIRONMENT !== 'production'), 'cache_on' => FALSE, 'cachedir' => '', 'char_set' => 'utf8', 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'encrypt' => FALSE, 'compress' => FALSE, 'stricton' => FALSE, 'failover' => array(), 'save_queries' => TRUE );OutputWhen I open this url "http://myworldmirror.com/", the output below is shown
404 page not found the page you requested was not found in codeigniter
You will do it in the same way you installed it in the root directory. I will tell you how I installed it on my shared hosting account, both main and sub domains. After I uploaded all my project to the subfolder, and your will beexample.com/ru, do the following:In your public folder there is your.htaccessfile. since you are basically making this a subdomain, it will need to be in the root of that subdomain, so transfer the.htaccessfrom public folder to the root ofrufolder.Open the.htaccessand change/add the following:DirectoryIndex public/index.phpand in theRewriteRulechange it to this:public/index.phpAnd just to be clear, your.htaccessshould be like this at the end after your changes:DirectoryIndex public/index.php <IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews </IfModule> RewriteEngine On # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)/$ /$1 [L,R=301] # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ public/index.php [L] # Handle Authorization Header RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] </IfModule>
I install laravel app in root of my shared host "public_html now I want to install Russian version of this app in ru/ subfolder but when I go to example.com/ru I got 404 Page not found error. I use apache web server my .htaccess file in root folder contain these code<IfModule mod_rewrite.c> RewriteEngine On RewriteRule ^(.*)$ public/$1 [L] </IfModule>how should i change this configuration?Thanks.
How to install laravel app in subfolder of shared host?
Rather than using a complicated regex I suggest usingNC(no case) flag to make your rule ignore case:RewriteRule ^about-us/?$ about-us.php [L,NC]
I am curious to know how to write a regex to replace the following I use for .htaccess managing my page urls. The point of the Regex is to identify any combination of letters whether they are upper or lower case so that I don't have to think of each combination like the following example....RewriteRule ^(about-us|About-Us|About-us|ABOUT-US)$ about-us.php [L]However what if I dont think of a combo, how can I write a regex that does this?So far the closest I have come is...^([about\-us|ABOUT\-US])$ about-us.php [L]
How to create a regex that looks for a word in any combination?
If you want to stay on the same Url, use absolute path instead of the full url for error handler .changeErrorDocument 404 http://blablabla.com/404.phptoErrorDocument 404 /404.phpThis will rewrite error pages to /404.php
i have a problem when creating custom 404 not found.so, i had try with .htaccess :ErrorDocument 404 http://blablabla.com/404.phpit's working!but the problem was it's using REDIRECT. whenever i type blablabla.com/sdkfsdkjfksdhfksdit's redirect to blablabla.com/404.phpit's changing thecurrent URL, that's not cool. it's ugly.what i suppose to do :whenever i type blablabla.com/sdkfsdkjfksdhfksdNO REDIRECT, STAY ON SAME URL. justrequire_oncecustom404.phppage.so, i try this code :<?php header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found"); require_once "404.php"; ?>i put it on top before anycode. and this method not working. it's showing on every single page. i try type on URL blablabla.com/sdfjnsfjnksdfthe page show up withObject not found!The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.If you think this is a server error, please contact the webmaster.how to get this things done?what's wrong with my code?thanks in advance...
PHP 404 not found page with no redirect + include page
Apache accesses and processes the htaccess files on each request. This is why one does not need to restart the server every time to check their current configurations.You do need to restart the server/service for testing any changes made toapache.conf,httpd.confor the vhost configurations.Quoting fromApache's tutorial onhtaccessfile:You should avoid using.htaccessfiles completely if you have access to httpd main server config file. Using.htaccessfiles slows down your Apache http server. Any directive that you can include in a.htaccessfile is better set in aDirectoryblock, as it will have the same effect with better performance.Since you already are trying toIncludethehtaccessfrom inside a<Directory>module block, the performance would be better if you include everything from the file to this block itself instead. There is, although no difference; apart from having to maintain configurations in two places simultaneously.Thehtaccessfile will get processed just once, at the time of server start.
Suppose we have the/home/example.org/public_html/directory on the filesystem, which serves as the document root of my virtualhost.The relevant httpd configuration for that vhost would look like this:<VirtualHost *:80> ServerName example.org:80 ... DocumentRoot /home/example.org/public_html <Directory /home/example.org/public_html> AllowOverride All ... </Directory> ... </VirtualHost>In order to prevent the htaccess lookups on the filesystem without losing the htaccess functionality – at least at the DocumentRoot level- I transformed the configuration to the following:<VirtualHost *:80> ServerName example.org:80 ... DocumentRoot /home/example.org/public_html <Directory /home/example.org/public_html> AllowOverride None Include /home/example.org/public_html/.htaccess ... </Directory> ... </VirtualHost>DifferenceAllowOverride None Include /home/example.org/public_html/.htaccessLet’s see what we have accomplished with this:httpd does not waste any time looking for and parsing htaccess files resulting in faster request processingQuestions:UsingIncludedirective, Apache load htaccess only on service start or for each request?If point 1 it's true, how do refresh apache conf withouthttpd.exe -k restart?
Apache: include htaccess in conf with AllowOverride None, better performance?
I solved my problem, the solution is firstly (in my case) delete the three .htaccess files and edit this line in app/config/core.php//Configure::write('App.baseUrl', env('SCRIPT_NAME'));to this:Configure::write('App.baseUrl', env('SCRIPT_NAME'));it works for me, thanks guys anyway.
I just uploaded my website to the server but is not loading the css and js files, only I can see the site just like text and after put the .htaccess files in their places I got this message in the site:Internal Server ErrorThe server encountered an internal error or misconfiguration and was unable to complete your request.Please contact the server administrator, and inform them of the time the error occurred, and anything you might have done that may have caused the error.More information about this error may be available in the server error log.Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.These are my .htaccess files/www/<IfModule mod_rewrite.c> RewriteEngine on RewriteRule ^$ app/webroot/ [L] RewriteRule (.*) app/webroot/$1 [L] </IfModule>/www/app/<IfModule mod_rewrite.c> RewriteEngine on RewriteRule ^$ webroot/ [L] RewriteRule (.*) webroot/$1 [L]/www/app/webroot/<IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L]some idea why is not working? I hope you can help me, thank you.<?php echo $this->Html->css('bootstrap'); echo $this->Html->css('styles'); echo $this->Html->script('jquery'); echo $this->Html->script('bootstrap.min'); echo $this->fetch('meta'); echo $this->fetch('css'); echo $this->fetch('script'); ?>
CakePHP 2.6.0 is not loading CSS and JS files
I agree with @anubhava,RewriteRuleis far more powerful and more useful as a general tool. However, to answer your specific "better" criteria:more stableNothing in it.Redirect(mod_alias) has been around longer. (?)saferAgain, if you know what you're doing then one isn't any "safer" than the other.RewriteRuleis more complex so there is more room for error. One thing you should be wary of, however, is that you should never useRedirect(mod_alias) andRewriteRule(mod_rewrite) together in the same file. They belong to different modules and execute at different times. Using them together can produce unexpected results.fasterSome would argue thatRedirectis faster. It is a lot simpler.more acknowledged by 'community'Debatable.RewriteRulewould seem to be used more these days, but it does a lot more. And many will use it because that is what they always use. The Apache docs do recommend that if you are just doing a simple redirect then a mod_aliasRedirectis preferred:When not to use mod_rewriteYou should note that the two directives you posted above are not exactly the same.Redirectis prefix matching and anything after the match is automatically passed to the target URL. Whereas in yourRewriteRuleyou have used anchors to explicitly mark the start and end of the URL.
IntroFor a very very long time I have usedRewriteRuleas redirection command. For example I used this:RewriteRule ^some-page.html$ /new-page.html [R=301,L]But recently I've found other method, usingRedirectkeyword:Redirect 301 /some-page.html /new-page.htmlQuestionWhich method is better and should be used as primary tool?Better is considered by being:more stablesaferfastermore acknowledged by 'community'
RewriteRule versus Redirect - which is better?
As @Boaz said, PHP doesn't know what Apache is going to set later.You could use this approach to use the error code in PHP:ErrorDocument 400 /error.php?error=400 ErrorDocument 401 /error.php?error=401 ...And in PHP test$_GET["error"].
I'm trying to use Apache'sErrorDocumentto handle client and server errors by passing them toerror.php..htaccessErrorDocument 400 /error.php ... ErrorDocument 404 /error.php ... ErrorDocument 511 /error.phperror.phpvar_dump(http_response_code());So, I point my browser tomywebsite.com/noeutdhoaeu, which does not exist. The response from the server is404 Not Found, as you would expect. But PHP gives me200.What gives?Edit: I have this same exact code on my Apache-based localhost and it works just fine. That is the reason I am asking this question. PHP is completely aware that a 404 error has occurred in my local environment. On my hosted environment, however, PHP has no idea.
http_response_code() always returns 200, even on 404
very easy just go to your main directori example home/example go to the directory public html and then go to you setting by the fault the system goes to 754 you will have to change to 755 the last 5 is go ing to allow to get to the site. cheers
I have moved to a new host and setup everything, but when I try to access the site, I get the following403 ForbiddenerrorForbiddenYou don't have permission to access /webfiles on this server. Server unable to read htaccess file, denying access to be safeAdditionally, a404 Not Founderror was encountered while trying to use an ErrorDocument to handle the request.Any ideas on the problem?
Magento new host - 403 Forbidden - Server unable to read htaccess file
Either you specify a relative path, as you do now, but then you'd need to override it in every folder - or you need to specify a real absolute path, from the root of the filesystem, like:php_value auto_prepend_file "/var/www/mywebsite/php/includes/init.php"In this case it will always work as it is absolute.If you have trouble determining the absolute path, justecho __DIR__in one of your PHP files - it will show the absolute path it is currently in.
I'm using aauto_prepend_filedirective in my.htaccess, like so :php_value auto_prepend_file "includes/init.php"This is my folder's structure :/php /css/main.css /includes/init.php /lib/functions.php index.php .htaccessThis is working fine for all the files in the root, such asindex.php. However, it will not work for all the files that are not in the root, such asfunctions.phpthat is in thelibfolder.I am getting the following error :Warning: Unknown: failed to open stream: No such file or directory in Unknown on line 0 Fatal error: Unknown: Failed opening required 'includes/init.php' (include_path='.;C:\xampp\php\PEAR') in Unknown on line 0It seems like it can't find the file where it should be, which makes sense.I'm trying to point to the root of my project, but I don't know how I can do that within the.htaccess.I tried changing my.htaccessline to the following :#Same problem php_value auto_prepend_file "/includes/init.php" #Won't work for any page now php_value auto_prepend_file "/php/includes/init.php"What do I need to put in my.htaccessso that the path always work, no matter where I am in the hierarchy?
auto_prepend_file in htaccess not working for subdirectories
Replace following lineRewriteRule . /index.php [L]toRewriteRule . /b2b/index.php [L]andRewriteBase /toRewriteBase /b2b/
I am trying tocopythe root WP installation to a sub directory. (I changed the permalinks in the new copy database to the subdirectory links)The subdirectory will be root/b2b/When I try to reach the subdirectory I get redirected to a 404 page.This is the .htaccess in the root# BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule>In the subdirectory I currently have no .htaccess since everything that I tried is not working.I checked the other topics but none of them seems to work for me.
Wordpress Subdirectory giving 404
Ok, this is how I got it to work:# Block visits from semalt.com RewriteEngine on RewriteCond %{HTTP_REFERER} ^http://([^.]+\.)*semalt\.com [NC] RewriteRule (.*) http://www.semalt.com [R=301,L]
I have implemented the following code to htaccess but are still seeing referrers from semalt, such as:74.semalt.com 89.semalt.comThe code:# Block visits from semalt.com RewriteEngine on RewriteCond %{HTTP_REFERER} ^http://([^.]+\.)*semalt\.com [NC] RewriteRule .* - [F]Any idea how these referrers are bypassing this rule (which I found online) and how I can fully prevent them?
blocking semalt referrers with htaccess rules
As Amal commented below your question that dot in regex meansany characterand sinceRewriteRuleused regular expressions for URI pattern hence you will need to escape dot to make it match literal dot.However inmod_rewriterules there is way you can useRewriteCondto make it match literal stringswithout regular expressionsusing=sign before matching patten:Here is an example of your translated rule:RewriteCond %{REQUEST_URI} =/views/index.php RewriteRule ^ /views/index.xml [L]
I have the following htacces to rewrite a precise URL (views/index.php to views/index.xml):RewriteEngine On RewriteRule ^/views/index\.php$ /views/index.xml [L]It's way too easy to forget the\and type^/views/index.php$, allowing/views/indexXphpand/views/index/phpinstead of only/views/index.php.Using an exact match instead of a regex is fine for my case, so would be a way to tell Apache thatfor all RewriteRules below / for this RewriteRule, the dot means a . not any character so the dot is not escaped.So,is there a way to have the exact match/views/index.phpwithout the need to escape the dot?
Exact match with RewriteRule without regex
You can combine both rules into one usingORcondition clause:RewriteEngine On RewriteCond %{HTTPS} off [OR] RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^ https://www.domain.com%{REQUEST_URI} [R=301,L,NE]Just replacewww.domain.comwith your actual domain name. Also it is better to test this in a new browser to avoid 301 caching issues.
I have two redirect conditions which work independently fine but I want to avoid the case where both conditions are satisfied (which results in two redirect steps instead of one)I must confess I am not good with Apache regex so I got them off the net. Any idea how to combine the two (A or B kinda logic with regex)?Here is the code:RewriteEngine On # redirect from http to https RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} # redirect from non-www to www https RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]Output of the multiple redirect result when both conditions are satisfied is shown below:
How to combine two Apache htaccess redirect conditions (http to https and non-www to www)
it redirects to the first SSL website in the apache conf file.This is because there are 2 sets of virtual hosts you have for apache: 1 that listens to port 80 (non-SSL) and one that listens to port 443 (SSL). Any non-SSL request gets sent to the vhosts that listens to port 80, and any SSL request gets sent to the chosts that listens to port 443. When a request is made for a host that isn't defined in any of the vhosts, it defaults to the "default" vhost, which becomes the very first one that gets defined (e.g. the first one that appears in your vhost file).In order to prevent this, you can either have a defined SSL vhost for each of your non-SSL websites, or you can create a new "default" vhost in your SSL file that does nothing but redirect to non-SSL:RewriteEngine On RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R]
I host 100+ websites on 2 different servers. Some of my clients recently have noticed that when they go tohttps://theirwebsite.com, if they DONT have SSL on their website, it redirects to the first SSL website in the apache conf file. I did some reading and discovered that SSL websites need their own IP addresses, so i switched the IP addresses of my SSL websites. However, i noticed that the problem is still happening. It's possible that there are still SSL websites that need to be removed or changed in httpd.conf, but is there a way to stop this from happening? Can i find a way to just make websites without https redirect to nothing if https is used?
SSL redirects user to wrong website on apache
You're missinghttp://from yourwwwforcing rule. Also important is to have your www rule before other WP rules:# BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} ^domain\.com$ [NC] RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R=301] RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPressAlsodon't forget to change WP permalinks to havewwwin Site and Home URLs
I have a wordpress site accessed likehttp://example.com/but my client wants to have it accessed likehttp://www.example.com/I am finding this code as a solution# BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress RewriteEngine On RewriteCond %{HTTP_HOST} ^domain\.com$ [NC] RewriteRule ^(.*)$ www.domain.com/$1 [L,R=301]But I am getting an error of redirect loopCould you please advice me what am i doing wrong?
How to put www in front of a wordpress site url in htaccess?
Ok its not 100% bulletproof since HTTP REFERRER can be spoofed.Try this rule:RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com/ [NC] RewriteRule ^process/login\.php$ - [F,NC]
Not sure if this is possible, but...Lets say i have process/login.phpif a user visits that page directly i have a check to see if the user has come from posting a form etc. If not, they get 404'd.However i am now building up plenty of process scripts etc and they all require different checks as some are just included etc.Is there a way to 404 a user if they directly access any files? using htaccess?I know there isOptions -IndexesBut that only stops the showing of the files. You can still visit any of the files directly.If there isnt a stable way of doing it then i will manually go around all the files and secure them but would rather the user just cant see anything.
Stop direct access to all files in a folder, but allow ajax requests
As far as I know, there is no known security hole in Apache where something like this could slip through. Whatever is in your URL gets escaped before it's used inside Apache's engine.Also, different from those in the central server config, rewrites and redirections defined in.htaccesscan not "break out" of the current web root*, so even an accidental mis-written (or exploited)RewriteRulecould not be used to get hold of something that isn't supposed to be served publicly.* = see the description ofRewriteRule's behaviour inthe docs.
I'm brand new to Apache.I have the following.htaccessfileOptions -Indexes RewriteBase / RewriteEngine on RewriteRule ^([a-zA-Z0-9_]+)*$ redirect.php?uniqueID=$1 [QSA,L]so that going to:mySite.com/242skl2jloads the page:mySite.com/redirect.php?uniqueID=242skl2jBut let's say I didn't have this RegEx in my Apache code[a-zA-Z0-9_]and I just allowed for all characters.... could someone load Apache code directly into this by navigating to something likemySite.com/2%20[R]%20reWriteRule%20^([a-zA-Z0-9_]+)*$%[email protected]/index.htmlLike SQL injection but for Apache? (I'm not even sure%20would convert to a space in my apache code but there might be something that can?)Or is this not really a concern because they can't do any real "harm" to the site, only to their own unique navigation?
Could a manipulated URL cause security issues inside a RewriteRule?
You can't use htaccess or mod_rewrite to remove URL fragments because they arenever sent to the server. As far as the server is concerned, they don't exist. You'll need to use javascript or some other client side solution to remove them.For example, from:Remove fragment in URL with JavaScript w/out causing page reload// remove fragment as much as it can go without adding an entry in browser history: window.location.replace("#"); // slice off the remaining '#' in HTML5: if (typeof window.history.replaceState == 'function') { history.replaceState({}, '', window.location.href.slice(0, -1)); }
I am trying to remove the anchor tags used when toggling the accordions or a link that includes an anchor to another part of the page.http://rivo.wpengine.com/why-rivo/#toggle-id-3I would like to removing the#toggle-id-3part of this URL.Can I do something with the.htaccessfile, maybe using mod_rewrite?
How do you remove anchor tags from URL?
The (technically) right wayConstruct a URI consisting of the current scheme (http/https/ etc), hostname and path of the current file and issue aLocationheader.$url = sprintf('%s://%s%s/index.php', $_SERVER['SERVER_PORT'] == 80 ? 'http' : 'https', $_SERVER['SERVER_NAME'], rtrim(dirname($_SERVER['PHP_SELF']), '/')) header("Location: $url"); exit;This is because a location header URI should be complete and absolute. Relative URIs are technically not allowed however there is a draft specification set to change this.The pragmatic wayJust issue a relativeLocationheader as it will most probably work.header('Location: index.php'); exit;
I need to redirect toindex.phpof whichever directory is requested.So I need:http://www.site.com/folder/files/hello.phpTo Redirect to:http://www.site.com/folder/files/index.phpAnd also same for any subfolders:http://www.site.com/folder/files/pages/other/hello.phpRedirect to:http://www.site.com/folder/files/pages/other/index.php
Redirect to index.php of requested subfolder
If you want access tohttp://example.com/subdirectoryjust by typinghttp://example.comthis should work.# .htaccess main domain to subdirectory redirect RewriteEngine on # Change example.com to be your main domain. RewriteCond %{HTTP_HOST} ^(www.)?example.com$ # Change 'subdirectory' to be the directory you will use for your main domain. RewriteCond %{REQUEST_URI} !^/subdirectory/ # Don't change the following two lines. RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # Change 'subdirectory' to be the directory you will use for your main domain. RewriteRule ^(.*)$ /subdirectory/$1 # Change example.com to be your main domain again. # Change 'subdirectory' to be the directory you will use for your main domain # followed by / then the main file for your site, index.php, index.html, etc. RewriteCond %{HTTP_HOST} ^(www.)?example.com$ RewriteRule ^(/)?$ subdirectory/ [L]
I am currently hosting a website using theSilex frameworkon a shared server and I have a problem...Silex is like Symfony, there is an app.php file located in a /web/ subfolder : the website is then only accessible via the URL website.com/web/. I cannot create a virtual host as it is a shared server, so I think the solution is to use an .htaccess file...I managed to redirect website.com to website.com/web/ automatically but I don't really like this option. I would rather website.com pointed directly to website.com/web/ but I don't know how to do this by just using a .htaccess file. I have been trying to solve this problem for hours now and it's killing me...At the moment I use this file :<IfModule mod_rewrite.c> Options -MultiViews RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ web/app.php [QSA,L] </IfModule>but it just redirects you from website.com to website.com/webIs there anyway I can make the root url directly point to the /web folder with a .htaccess file?Thank you very much :)
Use htaccess to redirect root to subfolder without showing it in URL
Use a negative look behind anchored to end:/^\/page\/test(.*)(?<!\.jpg)$/For clarity, this regex will match any input that *doesnt end in.jpg:^.*(?<!\.jpg)$Edit (now must work in JavaScript too)JavaScript doesn't support look behinds, so this ugly option must be used, which says that at least one of the last 4 characters must be other than.jpg:^.*([^.]...|.[^j]..|..[^p].|...[^g])$
I have those strings:"/page/test/myimg.jpg" "/page/test/" "/page2/test/" "/page/test/other"I want true for all strings starting with /page/test except when it ends with.jpg.Then I did:/^\/page\/test(.*)(?!jpg)$/. Well, it's not working. :\It should return like this:"/page/test/myimg.jpg" // false "/page/test/" // true "/page2/test/" // false "/page/test/other" // true
NOT a specific word at ending in regex
If that's the only rules you have in your htaccess file and it's in your document root then you need to check a few things because the rules are fine.Make sure mod_rewrite is loaded. There should be a line in yourhttpd.conffile that looks something like:LoadModule rewrite_module modules/mod_rewrite.soMake sure it's uncommented.Make sure the directory that your htaccess file is in (should be your document root) is allowed to override server settings via htaccess. In your vhost or server config, there should be something along the lines of<Directory "/var/www/"> AllowOverride All ... (some other stuff) </Directory>Make sure theAllowOverrideis at leastFileInfoMake sure your document root is actually where your htaccess file is in. Your vhost config should have a line like:DocumentRoot /var/www/Make sure the document root is for the right vhost. If you have separate vhosts for SSL and non-SSL, make sure the htaccess file is in the document rootfor the non-SSL vhost.
I'm trying to use.htaccessto send all traffic tohttps. I'm using the example in this answer:Need to redirect all traffic to httpsRewriteEngine on RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}This isn't redirecting anything for me. I placed it invar/wwwbut it doesn't seem to have any effect. What did I do wrong?
how do I force all traffic to https?
You have some options, and each has its own advantages.If you have a web app, which should not be indexed by search engines, then you are free to do whatever you want. You can keep a language setting in your Session and show strings in the chosen language. This will simplify URLs and management.However, if you have a standard website which should go into Google, then your options are restricted. If you use the former approach, google will be confused and will index only one language, or, worse, make an ugly mix of the languages. Google does not keep sessions when indexing your page, so if you have two versions of the same page in two different languages, they need to have different URLs. And passing a language as a GET parameter each time is ugly, error prone, and not user friendly.So you should either have languages as folders (eg. site.com/en/), which is the best options, or use subdomains. This can be a problem, however, because each subdomain is indexed as if it were a separate website, so things like pagerank and site reputation are split among the two.
They are some questions already about this on stackoverflow, but none is really clear about the 'best practice'.For the content design, what are the options and what is the better option?Some options I know are using folders: site.com/en/ and site.com/fr/ or redirects site.com/index.php?language=enAn even easier practice is using a new url: en.site.com and fr.site.comBut what if I want to keep site.com/index.php and nothing more ? What are my options for that?For example, if you change the language on LinkedIn, there's nothing changing in the URL. How do they work there ?update:in my case the website is a platform, using LAMP stack. Technical advice is also welcome (like how to store/link all the different language files)
Writing a mutiple language website: the webdesigner's (best) options
Try:RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ /index.php?request=$1 [L,QSA] RewriteCond %{REQUEST_FILENAME} !index\.php RewriteCond %{REQUEST_FILENAME} \.php$ RewriteRule ^(.*)$ /index.php?request=$1 [L,QSA]
I currently have redirects (using IIRF, but i believe this to be the same as .htaccess rules) set up so that all files don't get redirected, and just go straight to the filepath in the URL, but everything else gets redirected to /index.php Using the code below:RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ /index.php?request=$1 [L,QSA]I need it to also redirect any .php file (but only .php files) to index.php (same as the second rule)In summary, 'www.example.com/foo' AND 'www.example.com/foo.php' both need to go to the index page, but 'www.example.com/foo.js' and 'www.example.com/foo.css' (etc!) do not.
how do i redirect only php files with mod-rewrite (iirf)
make sure that AllowOverride is enabled (AllowOverride all) in httpd.conf (many distribs have default as none)if it is not that, you may have to post the actual htaccess for more help
I have defined some URL Rewriting rules in .htaccess fileIts working fine on localhost in windowsBut when I uploaded it on server that is linux based, it stopped to work I have found the problem on thislinkFiles and directory names starting with a dot are treated as hidden files by Unix, Linux & Mac. The htaccess file is hidden so it doesn’t distract from normal web content like HTML files. See hidden files for more information. Without the dot at the beginning, Apache will ignore the htaccess file.But I did not find the solution ...
.htaccess not working on linux
You need to put your redirect rulesbeforeyour routing rules. The rewrite engine loops so even if you have theLflag, it'll loop past your routing rules the second time around and hit the redirect rule, except this time, the URI has been rewritten already.If the rewrite rule is first, it'll redirect the browser before the routing rule gets applied. Then, when the redirected request is made, the routing rule gets applied. You'd also need aLflag.RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule .* index.php/$0 [PT,L]
Hey i'm using codeigniter and added rewrite rules to remove theindex.phpfrom the url which works fine.However, i've added a rule to redirect all http requests to https but when it does it redirects with the index.php.Meaning if i enter this url :domain.com/somecoolcontrolerIt will redirect me to :https://domain.com/index.php/somecoolcontrolerBut when navigating afterwards it comes back to normal urls without it so i guess the problem is in the redirect rule, this is what i put in htaccess :RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule .* index.php/$0 [PT,L] RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}How can i fix that?
htaccess redirects to https with index.php
Add a.htaccessin your/resources/folder containing the following<Files ~ "\.php$"> Order allow,deny Deny from all </Files>It should prevent access to all.phpfiles
I have a master folder where I hold all of my resources such as js, css, images, etc. called /resources/.In /resources/, I have php files I include on pages of my website, however, they're currently directly accessible if entered into the browser.Is there a way for me to use .htaccess in that directory to prevent direct requests to any files of certain extensions such as PHP? Hotlinking prevention isn't really what I'm looking for. I just need a way to kill any sort of direct request to these PHP files(in the /resources/ directory specifically) made by anything other than the website itself.Any help is appreciated. Thank you very much.
How to block direct requests to php files in specified directory?
Using this may be helpful:RewriteEngine On RewriteCond %{QUERY_STRING} q=(.*) RewriteRule ^q(.*) /download/%1.html [L,R=301]EDIT:Try this :)RewriteEngine On RewriteCond %{QUERY_STRING} q=(.*) RewriteRule ^(.*) /download/%1.html? [L,R=301]By using?query string will be removed ;)
I search many topic about htaccess but still not success.I want when people type address:http://domain.com/?q=filename1 http://domain.com/?q=filename2 ...It will auto redirect to:http://domain.com/download/filename1.html http://domain.com/download/filename2.html ...I try:RewriteEngine On RewriteRule ^/?q=(.*)$ /download/$1.html [L,R=301]But it is not working. How can I fix this?
htaccess - redirect query string and remove it from URL
Enable mod_rewrite and .htaccess throughhttpd.confand then put this code in your.htaccessunderDOCUMENT_ROOTdirectory:Options +FollowSymLinks -MultiViews # Turn mod_rewrite on RewriteEngine On RewriteBase / RewriteRule ^(folder)/(img/[^.]+\.jpg)$ $1/some.php?img=$2 [L,QSA,NC]Make sure:.htaccess is enabledmod_rewrite is enabledYour URL ishttp://example.com/folder/img/test.jpg
I'm looking for a way to rewrite all my image requests from onefolderintosome.phpfile, while preserving the original image url (or partial path).So,example.com/folder/img/test.jpgwould be rewrited as something likeexample.com/folder/some.php?img=img/test.jpg(is this the best approach?)I'm not familiarized enought witrh regular expressions, so I'll be very thankfull :)note :I've tried some solutions before, none of them worked. ALso, I'm runningApache 2.0underCentOSenvironment.
Apache - rewrite images to php file with .htaccess
In yourpublic_htmldirectory's.htaccessfile, add these rules:RewriteEngine On RewriteCond %{REQUEST_URI} !^/myfolder RewriteRule ^/?([^/]+)$ /myfolder/$1 [L]
Insidepublic_htmldirectory I have a foldermyfolderand I have theindex.phpin that folder.All my site url readshttp://example.com/myfolder/page-nameI want it to rewritten ashttp://example.com/page-nameWhat rule should I write in.htaccessto achieve the same
Hiding a Sub Directory in URL
RewriteEngine On RewriteCond %{REQUEST_URI} !^/mapping_script.php RewriteRule ^(.*)$ /mapping_script.php?url=http://%{HTTP_HOST}%{REQUEST_URI} [L,QSA]You'd replacemapping_script.phpwith whatever this script of yours is called. If you don't need thehttp://domain.name/part of the URL, removehttp://%{HTTP_HOST}from the rule's target.
I want to capture the url via .htaccess & send that url as a query string to the page which will check the existence of the url from the DB.So my problem is i have a old site with www.example.org & this has 4200 old links that should be mapped with the new site www.example.net.Now i have created a url mapper app which has the old site urls (4200) mapped with the new one. In this url mapper app, i have an .htaccess which will capture the url before sending it to the app. Now here i want to capture the complete URL hit by the user which points to the old site & then the url is sent to one page with query string as complete url, which can be checked against the (4200) old urls & then redirected to the corresponding page of new site.How can i achieve this. To get the compelete URL in .htaccess & pass it to the page as request parameter.
.htaccess capture the current url & take the url as query string to a page
Your problem is, as you may have figured it out, that you're denying all the stuff, then allow the URI 'index.php', but not the URI '/' -- even though the '/' gets redirected to the index.php behind the scenes, it's still a different URI, and thus it should be allowed too.The easiest way to do it is using theFilesMatchdirective, like this:order allow,deny <FilesMatch "^(index\.php)?$"> allow from all </FilesMatch>The regex^(index\.php)?$means "index.php or nothing".
I would like to deny all files in a directory, but index.php (as being the default page).This solutions works almost:Deny from all <Files index.php> Order Allow,Deny Allow from all </Files>The only problem: 'upload/index.php' is now accessable, but '/upload/' isn't. How can I allow the default page with htaccess?
Deny all files, but index/default page with htaccess
This should work:RewriteEngine On RewriteRule ^detail/([^/]*)$ /index.php?page=details&id=$1 [L]
i want rewrite it with a .htaccess i have this url:../index.php?page=details&id=123456like this:../detail/123456but I do not really know how to do this. Could you help me to rewrite this url? or give me a simple example that I can understand how it works
how to rewrite a url with two variables using .htaccess
RewriteEngine On RewriteCond %{HTTPS} !=on RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L] RewriteCond $1 !^(index\.php|resources|robots\.txt) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L,QSA]RewriteEngine On"starts" rewriting.RewriteCondandRewriteRulework as pairs. Here, we send user to non-www version first, and cleans URLs.
I'm trying to get my htaccess rewrite rules to remove theindex.phpfrom the url AND also redirect thewww.requests to the non-www version.This is my htaccess which works fine with removing the index.php:RewriteEngine on RewriteCond $1 !^(index\.php|resources|robots\.txt) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L,QSA]And I came across another question on how to remove thewwwpart:RewriteEngine On RewriteCond %{HTTPS} !=on RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L]But I just cant seem to get them to play nicely together! Any advice/suggestions most appreciated!
Codeigniter htaccess to remove index.php and www
RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{DOCUMENT_ROOT}/_$1.php -f RewriteRule ^([^/]+)$ _$1.php [L]I changed*to+so requests for e.g. example.com/ will not redirect to_.php
I'm trying to get the requestedfilename without the pathwith htaccess for a RewriteCond.REQUEST_FILENAMEreturns the full absolute path, but I only need the filename liketest.phpI've been searching for this a lot but couldn't find anything that helped me out. Thanks for any responses in advance!Edit:Im trying to do something like this:RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond _%{REQUEST_FILENAME}.php -f RewriteRule ^([^/]*)$ _$1.php [L]The URL typed in the browser looks like this:http://example.org/testThe File that will be requestested by the RewriteRule is:http://example.org/_test.phpWithRewriteCond _%{REQUEST_FILENAME}.php -fi tried to checkif the file existsfirstBasically I want to do this:URI:/test/blahCheck if _test.phpexists (with underscore!)
htaccess get filename without path
I found this solution elsewhere:RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.html -f RewriteRule ^(.*)$ $1.htmlsources: 1)http://www.catswhocode.com/blog/10-useful-htaccess-snippets-to-have-in-your-toolbox2)http://eisabainyo.net/weblog/2007/08/19/removing-file-extension-via-htaccess/
Trying to remove .html extensions from the site using .htaccess. So for example: www.mysite.com/charts.html would become www.mysite.com/chartsThe following script is in the .htaccess file:RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)\.html$ /$1 [L,R=301]But when the url without the .html extension is entered in the browser, it shows a 403 Forbidden error. Any help would be appreciated.
Trouble removing .html URL extension using .htaccess
You definitely should not useRflag if you don't want to change URL in browser. However even withoutRflag your RewriteRule will loop infinitely and you will eventually getinternal server error. Use RewriteRule like this:RewriteCond %{ENV:REDIRECT_STATUS} !200 RewriteRule ^images/(.*)$ images/%{HTTP_HOST}/$1 [L,NC]Which is using a special internal variable called{ENV:REDIRECT_STATUS}that is set to 200 once RewriteRule rule is applied successfully.
We are running multiple domains through the same code and we want to save their images in their respective folders. Here's what we are doing./images/www.domain1.com/logo.jpg /images/www.domain2.com/logo.jpgnow, what I want to know is, is this possible in htaccess that we rewrite the urls without user suspecting anything. This is what I want that<img src="/images/logo.jpg" />should internally become through htaccessRewriteRule ^images/(.*)$ /images/{HTTP_HOST}/$1 [L,R=301]But my question is,The above redirect continually loopsCan I achieve the img effect without user or admin suspecting anything?Sincerely,Khuram
htaccess redirect without user knowing
Macintosh UserAgents looks like something like this :Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7As far as I know,RewriteCond %{HTTP_USER_AGENT}will look for the regular expression you gave him. In the mentioned case, if he findsiPhonein the User-Agent, the condition test will return true. So it should be possible to do something like this :RewriteCond %{HTTP_USER_AGENT} Macintosh RewriteCond %{HTTP_HOST} ^www.example.com$ RewriteRule ^ http://mac.example.com%{REQUEST_URI} [R]Hope this works, and hope this helps :)
Quick search revealed many guides explaining how to detect an iPhone or iPad:RewriteEngine on RewriteCond %{HTTP_USER_AGENT} iPhone RewriteRule .* http://iphone.example.com/ [R]but is there any way to detect a Mac user (any browser), and redirect him?
Detect Mac users - htaccess
For that functionality in php, you needmod_rewriteor the equivalent in your webserver of choice, and to rewrite the url path into a get param instead.Google "clean urls drupal", for an example of it in the wild.
I am after a way of using the directories in the URL as PHP variables. Similar to Wordpress (if not all blogging platforms) I want a way to, say, pass domain.com/directory into a php file.The reason for this is so that when I create my own blog things, the URLs will be SEO friendly.Forexample, instead ofdomain.com/?blog=1&foo=1&bar=1&foobar=5I wantdomain.com/1/1/1/5 or somethingwhere I can then use the explode function to get variables.
Use directories in url as php variables
found it:The+sign needs to be added to[^/]=>([^/]+)Options +FollowSymLinks RewriteEngine on RewriteRule ^member\-([0-9]+)\-([^/]+)\.htm(l)?$ view_profile.php?id=$1 [NC,L]You can also add the extra charsjaneinmember-8222-jaane.htmlby using the $2 like:RewriteRule ^member\-([0-9]+)\-([^/]+)\.htm(l)?$ view_profile.php?id=$1&extra=$2 [NC,L]
Using the answer I received fromrcs20in myprevious postwhen I add this entry to my .htaccess file I see the error 404 Not Found:Options +FollowSymLinks RewriteEngine on RewriteRule ^member\-([0-9]+)\-([^/])\.htm(l)?$ view_profile.php?id=$1 [NC,L]The URL I'm passing it is:mysite/member-8222-jane.htmlAny idea why this might be happening. My old rewrite rule works fine:RewriteRule view_profile=(.*)$ view_profile.php?id=$1
Rewrite rule for Apache not finding URL?
Use this .htaccess code to have recursion based translation ofkey/valuebased URI:Options +FollowSymLinks -MultiViews RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([^/]+)/([^/]+)(/.*)?$ $3?$1=$2 [N,QSA] RewriteRule ^(/[^/]+|[^/]+/|/?)$ /index.php [L,QSA]Using these rules a URL ofhttp://localhost/n1/v1/n2/v2/n3/v3/n4/v4will be INTERNALLY redirected tohttp://localhost/?n4=v4&n3=v3&n2=v2&n1=v1treating each pair of URL segments separated by / as a name-value pair for QUERY_STRING. BUT keep in mind if URI doesn't have even number of segments eg:http://localhost/n1/v1/n2/then it will be redirected tohttp://localhost/?n1=v1, discarding extra n2.
I've seen it before where a rule was used to convert directories on a URL to key=value request queries.I have no idea how to do this so I can have more than one of these pairs.For example:http://www.example.com/mykey/myvalue/mykey2/myvalue2Would map to:http://www.example.com?mykey=myvalue&mykey2=myvalue2Thanks.
.htaccess rewrite to convert directories into /key/value/key/value
The answer might be a bit late but:RewriteCond %{REMOTE_HOST} !(123\.456\.789\.101|123\.456\.789\.102|123\.456\.789\.103)works well.
I currently have a wordpress site that is being upgraded and I have a maintenence redirect setup in the .htaccess file.I can allow my own IP access the site and admin but how can I allow multiple IPs access for the other editors to also have access.I'm currently using :RewriteEngine on RewriteCond %{REMOTE_HOST} !^123.456.789.101 #RewriteCond %{REMOTE_ADDR} !^123.456.789.101 RewriteCond %{REQUEST_URI} !/maintanence.html$ [NC] RewriteCond %{REQUEST_URI} !.(jpe?g?|png|gif) [NC] RewriteRule .* /maintanence.html [R=302,L]
Allow multiple IPs to access Wordpress Site Admin via .htaccess
RewriteCond %{HTTP_HOST} !work.example.com [NC] RewriteRule ^(.*)$ http://work.example.com/$1 [R=301,L,QSA]This will also remove the www from www.work.example.comNot sure if the QSA is needed, but I think it will prevent play.example.com/?home from being redirecting to work.example.com/ instead of work.example.com/?home
I have a site that has two domains pointing to it, let's call them:work.mysite.com play.mysite.comThis is bad practice, so I want to choosework.mysite.comand make it the canonical URL, permanently redirectingplay.mysite.comto it.I'm in the root directory for these two domains, in a .htaccess file, banging my head against the cement floor and wishing I wasn't here. Here's what I am currently trying. Tell me how totally wrong I am, please?<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} ^(www\.)?play\.mysite\.com [NC] RewriteRule ^/?(.*)?$ http://work.mysite.com/$1 [R=301] </IfModule>That gets me a really pretty 500 Internal Server Error. How far off am I?
How do I redirect one subdomain to another, when they both point to the exact same files?