Response
stringlengths
8
2k
Instruction
stringlengths
18
2k
Prompt
stringlengths
14
160
Use a snippet like:RewriteEngine on RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [NC,L] RewriteRule ^(.*) /index.html [NC,L]This will skip to the actual resource if there is one, and toindex.htmlfor all AngularJS routes.
I have an angular application with several routes, such as:site.com/ site.com/page site.com/page/4Using angular's html5 routing mode, these resolve correctly when you click links to them from within the application, but of course are 404 errors when you do a hard refresh. To fix this, I've tried implementing a basic htaccess rewrite.RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_METHOD} !OPTIONS RewriteRule ^(.*)$ index.html [L]This works for the angular requests, however when I try to load scripts or make ajax calls within my domain, such as:<script src="/app/programs/script.js"></script>This script doesn't load - it's request is redirected and it tries to load the index.html page as the .htaccess thinks it should reroute the request - not knowing that this file does exist and it should load the file instead of redirect.Is there any way I can have the htaccess redirect the request to index.html (with the view parameters) only if there is not an actual file that it should resolve to?
htaccess redirect for Angular routes
Try putting this in your.htaccessfile:RewriteEngine on RewriteCond %{HTTP_HOST} ^sub.domain.example RewriteRule ^(.*)$ /subdomains/sub/$1 [L,NC,QSA]For a more general rule (that works with any subdomain, not justsub) replace the last two lines with this:RewriteEngine on RewriteCond %{HTTP_HOST} ^(.*)\.domain\.example RewriteRule ^(.*)$ subdomains/%1/$1 [L,NC,QSA]
Is it possible to use.htaccessto rewrite a sub domain to a directory?Example:http://sub.domain.example/shows the content ofhttp://domain.example/subdomains/sub/
.htaccess rewrite subdomain to directory
.htaccess flag listC (chained with next rule)CO=cookie (set specified cookie)E=var:value (set environment variable var to value)F (forbidden - sends a 403 header to the user)G (gone - no longer exists)H=handler (set handler)L (last - stop processing rules)Last rule: instructs the server to stop rewriting after the preceding directive is processed.N (next - continue processing rules)NC (case insensitive)NE (do not escape special URL characters in output)NS (ignore this rule if the request is a subrequest)P (proxy - i.e., apache should grab the remote content specified in the substitution section and return it)PT (pass through - use when processing URLs with additional handlers, e.g., mod_alias)R (temporary redirect to new URL)R=301 (permanent redirect to new URL)QSA (append query string from request to substituted URL)S=x (skip next x rules)T=mime-type (force specified mime type)Flags are added to the end of a rewrite rule to tell Apache how to interpret and handle the rule. They can be used to tell apache to treat the rule as case-insensitive, to stop processing rules if the current one matches, or a variety of other options. They are comma-separated, and contained in square brackets.
QSA means that if there's a query string passed with the original URL, it will be appended to the rewrite (olle?p=1 will be rewritten as index.php?url=olle&p=1.L means if the rule matches, don't process any more RewriteRules below this one.Hi, what are some easy examples to explain the use of L? I can't seem to grasp this explanation above. Any help will be highly appreciated. Thanks.
What is L in [QSA, L] in htaccess
Are you sure, you want to do that? Even css and js files and images and ...?OK, first check if mod_access in installed to apache, then add the following to your .htaccess:Order Deny,Allow Deny from all Allow from 127.0.0.1 <Files /index.php> Order Allow,Deny Allow from all </Files>The first directive forbids access to any files except from localhost, because ofOrder Deny,Allow, Allow gets applied later, the second directive only affects index.php.Caveat: No space after the comma in the Order line.To allow access to files matching *.css or *.js use this directive:<FilesMatch ".*\.(css|js)$"> Order Allow,Deny Allow from all </FilesMatch>You cannot use directives for<Location>or<Directory>inside .htaccess files, though.Your option would be to use<FilesMatch ".*\.php$">around the first allow,deny group and then explicitely allow access to index.php.Update for Apache 2.4:This answer is correct for Apache 2.2. In Apache 2.4 theaccess control paradigmhas changed, and the correct syntax is to useRequire all denied.
I want to deny direct access to all.phpfiles except one:index.phpThe only access to the other.phpfiles should be through phpinclude.If possible I want all files in the same folder.UPDATE:A general rule would be nice, so I don't need to go through all files. The risk is that I forget a file or line.UPDATE 2:Theindex.phpis in a folderwww.myadress.com/myfolder/index.phpI want to deny access to all.phpfiles inmyfolderand subfolders to that folder.
Deny direct access to all .php files except index.php
For a302 Found, i.e. a temporary redirect do:header('Location: http://www.example.com/home-page.html'); // OR: header('Location: http://www.example.com/home-page.html', true, 302); exit;If you need a permanent redirect, aka:301 Moved Permanently, do:header('Location: http://www.example.com/home-page.html', true, 301); exit;For more info check the PHP manual for theheader functionDoc. Also, don't forget to callexit;when usingheader('Location: ');But, considering you are doing a temporary maintenance (you don't want that search engines index your page) it's advised to return a503 Service Unavailablewith a custom message (i.e. you don't need any redirect):<?php header("HTTP/1.1 503 Service Unavailable"); header("Status: 503 Service Unavailable"); header("Retry-After: 3600"); ?><!DOCTYPE html> <html> <head> <title>Temporarily Unavailable</title> <meta name="robots" content="none" /> </head> <body> Your message here. </body> </html>
I'm considering using the following code during a website launch phase to show users adown for maintenancepage while showing me the rest of the site.Is there a way to show the correct 302 re-direction status to search engines or should I look for another.htaccessbased approach?$visitor = $_SERVER['REMOTE_ADDR']; if (preg_match("/192.168.0.1/",$visitor)) { header('Location: http://www.yoursite.com/thank-you.html'); } else { header('Location: http://www.yoursite.com/home-page.html'); };
301 or 302 Redirection With PHP
I guess it's meant that you enable gzip compression for your css and js files, because that will enable the client to receive both gzip-encoded content and a plain content.This is how to do it in apache2:<IfModule mod_deflate.c> #The following line is enough for .js and .css AddOutputFilter DEFLATE js css #The following line also enables compression by file content type, for the following list of Content-Type:s AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml #The following lines are to avoid bugs with some browsers BrowserMatch ^Mozilla/4 gzip-only-text/html BrowserMatch ^Mozilla/4\.0[678] no-gzip BrowserMatch \bMSIE !no-gzip !gzip-only-text/html </IfModule>And here's how to add theVary Accept-Encodingheader:[src]<IfModule mod_headers.c> <FilesMatch "\.(js|css|xml|gz)$"> Header append Vary: Accept-Encoding </FilesMatch> </IfModule>TheVary:header tells the that the content served for this url will vary according to the value of a certain request header. Here it says that it will serve different content for clients who say theyAccept-Encoding: gzip, deflate(a request header), than the content served to clients that do not send this header. The main advantage of this, AFAIK, is to let intermediate caching proxies know they need to have two different versions of the same url because of such change.
Google PageSpeed says I should "Specify a Vary: Accept-Encoding header" for JS and CSS. How do I do this in .htaccess?
How to Specify "Vary: Accept-Encoding" header in .htaccess
www to non www with httpsRewriteEngine on RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ https://%1/$1 [R=301,L] RewriteCond %{ENV:HTTPS} !on RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
I've got several domains operating under a single.htaccessfile, each having an SSL certificate.I need to force ahttpsprefix on every domain while also ensuringwwwversions redirect tono-wwwones.Below is my code; it doesn't work:RewriteCond %{HTTP_HOST} ^www.%{HTTP_HOST} RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI}/$1 [R=301,L]What I want to achieve is to: redirect something likehttps://www.example.comtohttps://example.com.What am I doing wrong and how can I achieve it?
.htaccess redirect www to non-www with SSL/HTTPS
Try thismod_rewriterule:RewriteEngine on RewriteRule !^uploads($|/) http://example.com%{REQUEST_URI} [L,R=301]This rule does match any URL path that doesnotbegin with either/uploadsor/uploads/(leading/is missing in the pattern due to the path prefix removal when used in .htaccess files) and redirects the request to the corresponding path atexample.com.
I want to 301 redirect an entire website, but exclude everything in a folder called/uploadswhich exists in the/rootdirectory.I have googled for this, but didn't come up with anything, or I didn't think what I saw was right.Can we crack this?
Redirect site with .htaccess but exclude one folder
Attempt 2 was close to perfect. Just modify it slightly:RewriteEngine On RewriteCond %{HTTPS} on RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]UPDATE:Above solution works from a technical point of view.BUT:Since a few years now the user will receive a huge warning indicating that the connection is not private. That is to be expected: none of today's browsers will silently switch from an encrypted to a not encrypted connection, for obvious reasons ... You cannot get around that behavior of standard browsers. That however has nothing to do with the redirection itself. It is how the web works today, how users are protected from criminal intents.
I'm trying to redirecthttps://www.example.comtohttp://www.example.com. I tried the following code in the .htaccess fileRewriteEngine On RewriteCond %{HTTP_HOST} ^example\.com$ [NC] RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]This code successfully redirectshttps://example.comtohttp://www.example.com. However when I type inhttps://www.example.comthen it gives me a "web page not available" error in the browser.I have also tried the following 2 codes without successAttempt 1RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^/(.*):NOSSL$ http://www.example.com/$1 [R=301,L]Attempt 2RewriteEngine On RewriteCond %{HTTPS} on RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}Both above attempts failed. Any suggestions?
Https to http redirect using htaccess
Deny from allis an .htaccess command (the actual content of that file you are trying to view). Not a denial of being able to edit the file. Just reopen the.htaccessfile in the text viewer of choice and make the alterations as you so desire, save it, then reupload it to your folder of choice.Though I think inadvertently you are blocking even yourself from viewing said application once uploaded.I would do something like:order deny,allow deny from all allow from 127.0.0.1which will deny everyone but the IP in theallow fromline, which you would change the IP to match your IP which you can obtain fromhttp://www.whatismyip.com/or similar site.
I have copied one of my old applications and renamed it toNew_application. I want to access.htaccessfile that is inside theNew_applicationfolder. When I opened it with my text editor, it just showedDeny from all. I tried to open.htaccessin my old application, it showedDeny from alltoo. I remember I was able to edit it before but not sure what I can't now. Any thoughts? Thanks a lot.
.htaccess deny from all
Try to disable theengineoptionin your .htaccess file:php_flag engine off
I'm making a website which allows people to upload files, html pages, etc... Now I'm having a problem. I have a directory structure like this:-/USERS -/DEMO1 -/DEMO2 -/DEMO3 -/etc... (every user has his own direcory here) -index.php -control_panel.php -.htaccessNow I want to disable PHP, but enable Server-side includes in the direcories and subdirectories inside /USERSCan this be done (and if so, how)?I use WAMP server
Disable PHP in directory (including all sub-directories) with .htaccess
Try the following:RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]Also, you can also redirect based on port number, for example:RewriteCond %{SERVER_PORT} ^80$ RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]This will redirect all requests received on port 80 to HTTPS.
I've had a look through existing questions, but I haven't really come across anything which works for me.I'm currently running a site with a Secure SSL certificate. It can be accessed athttps://www.example.co.uka problem is the site can also be accessed athttp://www.example.co.uk- I don't want this to be possible. I need it to redirect from http to https.I found this one snippet of code to use in an .htaccess file.Options +FollowSymLinks RewriteEngine on RewriteCond %{HTTP_HOST} ^example.co.uk [NC] RewriteRule ^(.*)$ https://example.co.uk/$1 [L,R=301]This works fine when the user enters example.co.uk into their address bar, but I also need to add a conditional statement of some sort so that if the user enters 'www.example.co.uk' or 'http://www.example.co.uk'.I've tried using the likes of [OR], but this ends up creating server errors.Any help and suggestions is appreciated.Cheers.
http to https through .htaccess
Apache denies all URLs with%2Fin the path part, for security reasons: scripts can't normally (ie. without rewriting) tell the difference between%2Fand/due to thePATH_INFOenvironment variable being automatically URL-decoded (which is stupid, but a long-standing part of the CGI specification so there's nothing can be done about it).You can turn this feature off using theAllowEncodedSlashesdirective, but note that other web servers will still disallow it (with no option to turn that off), and that other characters may also be taboo (eg.%5C), and that%00in particular will always be blocked by both Apache and IIS. So if your application relied on being able to have%2For other characters in a path part you'd be limiting your compatibility/deployment options.I am using urlencode() while preparing the search URLYou should userawurlencode(), noturlencode()for escaping path parts.urlencode()is misnamed, it is actually forapplication/x-www-form-urlencodeddata such as in the query string or the body of a POST request, and not for other parts of the URL.The difference is that+doesn't mean space in path parts.rawurlencode()will correctly produce%20instead, which will work both in form-encoded data and other parts of the URL.
About the systemI have URLs of this format in my project:-http://project_name/browse_by_exam/type/tutor_search/keyword/class/new_search/1/search_exam/0/search_subject/0Where keyword/class pair means search with "class" keyword.I have a common index.php file which executes for every module in the project. There is only a rewrite rule to remove the index.php from URL:-RewriteCond $1 !^(index\.php|resources|robots\.txt) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php [L,QSA]I am using urlencode() while preparing the search URL and urldecode() while reading the search URL.ProblemOnly the forward slash character is breaking URLs causing 404 page not found error. For example, if I searchone/twothe URL ishttp://project_name/browse_by_exam/type/tutor_search/keyword/one%2Ftwo/new_search/1/search_exam/0/search_subject/0/page_sort/How do I fix this? I need to keep index.php hidden in the URL. Otherwise, if that was not needed, there would have been no problem with forward slash and I could have used this URL:-http://project_name/index.php?browse_by_exam/type/tutor_search/keyword/one %2Ftwo/new_search/1/search_exam/0/search_subject/0
urlencoded Forward slash is breaking URL
Either the mainhttpd.confor the.htaccessfile in this directory or a nearby parent directory probably includes:Options -IndexesYour host may have to set it to+Indexesif you don't have access in.htaccessand want to list & browse the directory contents, absent a defaultindex.html, index.php, etc. If the directory should not have a default file and you don't enableIndexes, you may only directly target the filenames of contents within it.TheIndexesoption is commonly disabled by default on many Apache installations.Full details are available inthe Apache core documentation onOptions
I'm using the dompdf plugin for codeigniter:http://codeigniter.com/wiki/PDF_generation_using_dompdf/to generate pdfs from a form. This works on localhost, but on the live server I get this in the error log:Directory index forbidden by Options directive: /var/www/vhosts/domain.co.uk/httpdocs/mm/userdata/account1/invoices/Any idea what this means? I've searched for answers, and found a few that suggest editing the httpd.conf, however I don't have access to this.I've also tried adding a blank index.html file to the root and document directory (as also suggested elsewhere, but to no avail).Any help greatly appreciated.Thanks!
Directory index forbidden by Options directive
I had the same problem (trouble stripping 'www' from URLs that point to a sub-directory on an add-on domain), but after some trial and error, this seems to work for me:RewriteEngine on RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ http://%1%{REQUEST_URI} [R=301,QSA,NC,L]
This seems to be a non-issue for many people (read: I can't find an answer), but I would like to update the following htaccess code to not only remove the 'www' from the URL, but also any sub-directories that are accessed.RewriteEngine on RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L]With this,http://www.example.com/any/resolves fine, but I want it to redirect tohttp://example.com/any/as with the root.
.htaccess Remove WWW from URL + Directories
Most likely problem is this line:AuthUserFile /.htpasswdThis line should provide full filesystem path to the password file e.g.AuthUserFile /var/www/.htpasswdTo discover your filesystem path, you can create a PHP document containingecho $_SERVER['DOCUMENT_ROOT'];
I'm working on blocking a folder with .htaccess, which I've never used before, and I'm having some trouble. Here's what I have.htaccess (located in the folder I want blocked):AuthName "Username and password required" AuthUserFile /.htpasswd Require valid-user AuthType Basic.htpasswd (located at root, password is encrypted in actual file):tim:blahI'm getting 500 Internal Server errors with this and I can't figure out why.
.htaccess/.htpasswd 500 Internal Server Error
To switch to PHP 4.4:AddHandler application/x-httpd-php4 .phpTo switch to PHP 5.0:AddHandler application/x-httpd-php5 .phpTo switch to PHP 5.1:AddHandler application/x-httpd-php51 .phpTo switch to PHP 5.2:AddHandler application/x-httpd-php52 .phpTo switch to PHP 5.3:AddHandler application/x-httpd-php53 .phpTo switch to PHP 5.4:AddHandler application/x-httpd-php54 .phpTo switch to PHP 5.5:AddHandler application/x-httpd-php55 .phpTo switch to PHP 5.6:AddHandler application/x-httpd-php56 .phpTo switch to PHP 7:AddHandler application/x-httpd-php7 .phpTo switch to PHP 7.1:AddHandler application/x-httpd-php71 .php
I'm usingphp 5.3on my local machine. On our webserver we havephp 4.8. Our server is a shared server. So I want to change the php version on our server via.htaccessfile. Is it possible to do it? If yes how to do it?
how to change php version in htaccess in server
Try this:# redirect mail posting to index RewriteRule send-mail index.php?send-mail [NC,P]"P" acts like "L" in that it stops processing rules but it also tells the module that the request should be passed off to the proxy module intact (meaning POST data is preserved).
I have a website where all requests are redirected silently (via.htaccess) toindex.phpand then PHP is used to show the correct page (by parsing theREQUEST_URI).I was wondering if it's possible to submit POST data to a fake address too?I've currently got my form like so...<form action="/send-mail" method="post">And my.htaccessrule is...# redirect mail posting to index RewriteRule send-mail index.php?send-mail [NC,L]Myindex.phpchecksisset($_GET['send-mail'])which works fine.This however seems to drop off all the POST data that should be sent to it.Is there a way to keep the post data? I don't want to use GET because it can't send as much information, though it might not be an issue with a simple inquiry form.Here is my.htaccessfor redirecting toindex.php# serve files and dirs if they exist please, otherwise send to index RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule . index.php
Is it possible to redirect post data?
+50By default, the DirectoryIndex is set to:DirectoryIndex index.html index.htm default.htm index.php index.php3 index.phtml index.php5 index.shtml mwindex.phtmlApache will look for each of the above files, in order, and serve the first one it finds when a visitor requests just a directory. If the webserver finds no files in the current directory that match names in the DirectoryIndex directive, then a directory listing will be displayed to the browser, showing all files in the current directory.The order should beDirectoryIndex index.html index.php// default is index.htmlReference:Here.
I have the following line in my .htaccess file:DirectoryIndex index.html index.phpEverytime I go to index.php it takes me to index.html. Is it possible to allow for both, but leave index.html the default for users visiting www.domain.com?
Make index.html default, but allow index.php to be visited if typed in
PHP file (for example, my_lengthy_script.php)ini_set('max_execution_time', 300); //300 seconds = 5 minutes.htaccess file<IfModule mod_php5.c> php_value max_execution_time 300 </IfModule>More configuration options<IfModule mod_php5.c> php_value post_max_size 5M php_value upload_max_filesize 5M php_value memory_limit 128M php_value max_execution_time 300 php_value max_input_time 300 php_value session.gc_maxlifetime 1200 </IfModule>If wordpress, set this in the config.php file,define('WP_MEMORY_LIMIT', '128M');If drupal, sites/default/settings.phpini_set('memory_limit', '128M');If you are using other frameworks,ini_set('memory_limit', '128M');You can increase memory asgigabyte.ini_set('memory_limit', '3G'); // 3 Gigabytes259200 means:-( 259200/(60x60 minutes) ) / 24 hours ===> 3 DaysMore details on my blog
I have addedset_time_limit(0);function to increase execution time but its executing only 2-3 minutes maximum.error_reporting(E_ALL); error_reporting(1); set_time_limit(0);I want to search links from a site which is taking a long time.
Increase max execution time for php
Use this to add assets likecss,javascript,images.. into blade file.FOR CSS,<link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" >OR<link href="{{ URL::asset('css/app.css') }}" rel="stylesheet" type="text/css" >FOR JS,<script type="text/javascript" src="{{ asset('js/custom.js') }}"></script>OR<script type="text/javascript" src="{{ URL::asset('js/custom.js') }}"></script>FOR IMAGES,{{ asset('img/photo.jpg'); }}Here is theDOCAlternatively, if you pulled the composer packageilluminate/htmlwhich was come as default in laravel 4.2 then you can use like below, In laravel 5. you have to manually pull the package.{{ HTML::style('css/style.css') }}Here is anExample.
I've just installed a Laravel 5 project on MAMP and my pages are not finding the css files.This is the link to my css in my app.blade.php file:<link href="/css/app.css" rel="stylesheet">And my .htaccess file has this line:RewriteBase /laravel-site/laravel-5-app/public/In the config folder my app.php file contains this:'url' => 'http://localhost:8888/laravel-site/laravel-5-app/public/',But when I open up this page:http://localhost:8888/laravel-site/laravel-5-app/public/auth/loginand check the developer tools, it is looking for the css file at this location:http://localhost:8888/css/app.cssJust as a side note, if I go to this url:http://localhost:8888/laravel-site/laravel-5-app/public/I get the correct welcome page.
Laravel 5 not finding css files
Create a .htaccess file at the root of your website and add this line:[Apache2 @ Ubuntu/Debian: use this directive]AddType application/x-httpd-php .html .htmOr, from comment below:AddType application/x-httpd-php5 .html .htmIf your are running PHP as CGI (probably not the case), you should write instead:AddHandler application/x-httpd-php .html .htm
I need to run all of my .html files as .php files and I don't have time to change all of the links before our presentation tomorrow. Is there any way to "hack" this with my Apache server?
Using .htaccess to make all .html pages to run as .php files?
RedirectMatchuses a regular expression that is matched against the URL path. And your regular expression/contact.phpjust meansany URL path that contains/contact.phpbut not justany URL path that is exactly/contact.php. So use the anchors for the start and end of the string (^and$):RedirectMatch 301 ^/contact\.php$ /contact-us.php
After a site redesign, I've got a couple of pages that need to be redirected. Everything is staying on the same domain, just a couple of things have been reorganised and/or renamed. They are of the form:/contact.phpis now:/contact-us.phpUsing the .htaccess file, I've added this line, which is the one I find recommended most:RedirectMatch 301 /contact.php /contact-us.phpThis is mostly fine - it does the job - the problem is, it also redirects:/team1/contact.php/non-existant-folder/contact.phpIs there a way of specifying that I only want to redirect the contact.php in the root?
.htaccess 301 redirect of single page
For versions 2.2.X you can use the following...AuthUserFile /var/www/mysite/.htpasswd AuthName "Please Log In" AuthType Basic require valid-user Order allow,deny Allow from xxx.xxx.xxx.xxx satisfy anyObviously replace the path to your usersfile and the ip address which you would like to bypass the authentication.Further explanation of the specifics, can be found at:http://httpd.apache.org/docs/2.2/howto/auth.html
Is it possible to have an .htaccess/.htpasswd access control setup for a given directory, but if they are from a specific IP address, bypass the login/password authentication?I know you can do something like this in the .htaccess file:order deny,allow deny from all allow from 000.000.000.000But if you add something along these lines:AuthType Basic AuthName "restricted area" AuthUserFile /path/to/.htpasswd require valid-userThen it prompts for the password. Is there any way to do an if/else type setup, or some other solution so that users as a given IP (or set of IPs) don't get prompted for a password, but everyone else does?
.htaccess / .htpasswd bypass if at a certain IP address
Use Package Control to install the syntax packages you want to use. If you're using Sublime Text without Package Control, you're missing out on a lot.Install Package Control(follow the linked instructions)After restarting, typeCommand+Shift+PthenInstall PackageInstallApacheConfand theRobot Frameworkyou mentionedPackages can be added and removed very easily, but greatly enhance and personalize what you can do with Sublime Text.
Is there a way to colorcode/highlight robots.txt and .htaccess syntax? E.g. with a SublimeText2 plug-in. I found this, but can't figure out how to install it:https://github.com/shellderp/sublime-robot-plugin
robots.txt and .htaccess syntax highlight
Make sure that the htaccess file is readable by apache:chmod 644 /var/www/abc/.htaccessAnd make sure the directory it's in is readableandexecutable:chmod 755 /var/www/abc/
Hi all I'm using PHP for my website and ubuntu linux on my system. I got the above error in error.log file of apache, even after configurating everything properly. I did a lot of research on this but couldn't be able to resolve the issue. Can anyone please help me in this reagard? Following is my .htaccess file inabc directory. Can anyone please help me in this regard?# -FrontPage- IndexIgnore .htaccess */.??* *~ *# */HEADER* */README* */_vti* <Limit GET POST> order deny,allow deny from all allow from all </Limit> <Limit PUT DELETE> order deny,allow deny from all </Limit> AuthName abc.org AuthUserFile /home/abc/public_html/_vti_pvt/service.pwd AuthGroupFile /home/abc/public_html/_vti_pvt/service.grp Options -Indexes RewriteEngine On RewriteRule ^alumni$ alumni.php RewriteRule ^student$ student.php RewriteRule ^view_alumni_article/view/([0-9]+)$ view_alumni_article.php?op=view&article_id=$1
Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?
Go tohttpd.confon/Applications/MAMP/conf/apacheand see if theLoadModule rewrite_module modules/mod_rewrite.soline is un-commented (without the # at the beginning)and change these from ...<VirtualHost *:80> ServerName ... DocumentRoot /.... </VirtualHost>To this:<VirtualHost *:80> ServerAdmin ... ServerName ... DocumentRoot ... <Directory ...> Options FollowSymLinks AllowOverride None </Directory> <Directory ...> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all </Directory> </VirtualHost>
I am trying to get the.htaccessworking in MAMP. The content of the.htaccessis a simple redirect line, but the entire .htaccess file seems to have no effect, even when I change it to contain invalid data.Is there any settings within MAMP I need to change to enable.htaccessfiles?
How to get MAMP to read .htaccess files
The variable must be saved as an Apache var, then that can be used without repeated conditions.Saving in Apache variables are shown in second line. Usage of saved vars in 3th and 4th lines.RewriteCond %{HTTP_HOST} ^(www\.)?([a-z0-9-]+)\.example\.com [NC] RewriteRule .? - [E=Wa:%1,E=Wb:%2] RewriteRule ^(.*?)-([a-z]+) %{ENV:Wb}/$1.%{ENV:Wb} [L] RewriteRule ^(.*?)-([0-9]+)([a-z]) %{ENV:Wb}/$1$3.$2 [L]
I have following command in my .htaccessRewriteCond %{HTTP_HOST} ^(www\.)?([a-z0-9-]+)\.example\.com [NC] RewriteRule ^(.*?)-([a-z]+) %2/$1.$2 [L] RewriteRule ^(.*?)-([0-9]+)([a-z]) %2/$1$3.$2 [L]%2 is not working in second and later lines. Can I define any variable for %2 and use it in all RewriteRule commands? Following command worksRewriteCond %{HTTP_HOST} ^(www\.)?([a-z0-9-]+)\.example\.com [NC] RewriteRule ^(.*?)-([a-z]+) %2/$1.$2 [L] RewriteCond %{HTTP_HOST} ^(www\.)?([a-z0-9-]+)\.example\.com [NC] RewriteRule ^(.*?)-([0-9]+)([a-z]) %2/$1$3.$2 [L]But I want use %2 for multiple rule line without duplicating condition.
Multiple RewriteRules for single RewriteCond in .htaccess
You cannot use theDirectory directivein .htaccess. However if you create a .htaccess file in the /system directory and place the following in it, you will get the same result#place this in /system/.htaccess as you had before deny from all
I've been cleaning up my project lately. I have a main .htaccess in the root directory and 6 others. 5 of them ranOptions -Indexeswhich i didn't see anypoint of allowing any Directory viewing so moved that to the main one. so now i only have 2 .htaccess files. the main and one in/systemwhich holds# Block External Access deny from allSo i wanted to run that on/systemonly from within the main. So i deleted the one in /system and added# Block External Access <Directory "/system/"> deny from all </Directory>to my main .htaccess file leaving 1!but now i get aInternal Server ErrorThe server encountered an internal error or misconfiguration and was unable to complete your request.Please contact the server administrator, webmaster@localhost 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.Apache/2.2.17 (Ubuntu) Server at 10.0.1.5 Port 80The goal is to block reading any files in /system and it's sub directory's but allow viewing of everything else all from one.htaccessfile for the whole project. Any ideas on how i can fix this? I did some Google searches but couldn't really come out with anything.
htaccess <Directory> deny from all
Assuming your configuration has AllowOverrides with .htaccess, you must enable mod_env in Apache for this to work.Apache - mod_env
I am trying to set an environment variable in an .htaccess file and retrieve it in PHP. I've looked through a bunch of other threads here on SO but everything I've tried so far has failed.I've added this line to the .htaccess file:SetEnv SPECIAL_PATH /foo/binI have tried retrieving this value using the getenv() PHP function:<?php $specialPath = getenv('SPECIAL_PATH'); ?>I have runned phpinfo() to see the list of available environment variables, SPECIAL_PATH is not there. I am puzzled as to why this is not working.Thank you!
Set an environment variable in .htaccess and retrieve it in PHP
Although you can't use.htaccessor.conf,Github has instructions on how to usethe Jekyll Redirect From plugin.https://help.github.com/articles/redirects-on-github-pages/The page above no longer has any mention of the plugin. The direct link to the jekyll-redirect-from plugin GitHub repo ishttps://github.com/jekyll/jekyll-redirect-from
I understand that.htaccessis not supportedby GitHub Pages. Is there an alternative for password-protecting particular directories for websites hosted by GitHub Pages?
Is there an alternative to .htaccess for GitHub Pages?
Are you trying to get visitors to old.com/about.htm to go to new.com/about.htm? If so, you can do this with a mod_rewrite rule in .htaccess:RewriteEngine onRewriteRule ^(.*)$ http://www.thenewdomain.com/$1 [R=permanent,L]
I want to redirect all of my old domain request to my new domain using htaccess file. Below is what I am using but it does not work if the page is not on the new site. For example google index about.htm on the old site but on the new site it does not exist. I would like it to just go to the root in all cases. I know this is not ideal for seo but I don't want any 404s. Any suggestions?Redirect 301 / http://www.thenewdomain.com/
htaccess redirect all pages to single page
if you have long processing server side code, I don't think it does fall into 404 as you said ("it goes to a webpage is not found error page")Browser should report request timeout error.You may do 2 things:Based on CGI/Server side engine increase timeout therePHP :http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time- default is 30 secondsIn php.ini:max_execution_time 60Increaseapache timeout- default is 300 (inversion 2.4it is 60).In your httpd.conf (in server config or vhost config)TimeOut 600Note that first setting allows your PHP script to run longer, it will not interferre with network timeout.Second setting modify maximum amount of time the server will wait for certain events before failing a requestSorry, I'm not sure if you are using PHP as server side processing, but if you provide more info I will be more accurate.
How do I increase the apache timeout directive in .htaccess? I have a LONG $_POST['script'] that takes a user probably 10 minutes to fill in all the data. The problem is if it takes too long than the page times out or something and it goes to a webpage is not found error page. Would increasing the apache timeout directive in .htaccess be the answer I'm looking for. I guess it's set to 300 seconds by default, but I don't know how to increase that or if that's even what I should do... Either way, how do I increase the default time? Thank you.
How to increase apache timeout directive in .htaccess?
How to fix it in NGINX? client_max_body_sizeTo fix this, you need to increase the value of the client_max_body_size directive. This directive defines the maximum amount of data Nginx will accept in an HTTP request. By default this value is set to 1 megabyte, meaning if you attempt to upload a file larger than 1 megabyte you'll be getting an Error 413: Request entity too large page. You can insert this directive at three levels:In the http block: this will set the directive value for all server and locations in your configurationnIn the server block: this will set the directive value for all locations of one particular serverIn the location block: this will set the directive value for one specific location in a particular serverIn this example I'm going to insert it in my http block and set it to 500 megabytes:http { client_max_body_size 500M; # allows file uploads up to 500 megabytes [...] }source:http://cnedelcu.blogspot.com.ar/2013/09/nginx-error-413-request-entity-too-large.html
How to avoid this 413 error ?Request Entity Too LargeThe requested resource /serverpath/reports.php does not allow request data with POST requests, or the amount of data provided in the request exceeds the capacity limit.Apache Server at demo3.website_name Port 80So, could any one please help to set php.ini and how to set htaccess to allow overwrite status
How to avoid Request Entity Too Large 413 error
For .htaccess rewrite:http://learn.iis.net/page.aspx/557/translate-htaccess-content-to-iis-webconfig/Or try aping .htaccess:http://www.helicontech.com/ape/
Does anyone know if there is an equivalent to .htaccess and .htpassword for IIS ? I am being asked to migrate an app to IIS that uses .htaccess to control access to sets of files in various URLs based on the contents of .htaccess files.I did a google search and didn't turn up anything conclusive. Is there a general approach or tool that I need to purchase that provides this capability ?
.htaccess or .htpasswd equivalent on IIS?
FollowSymLinksmeans if a dir is a symbol link, follow the linkIndexesmeans a dir can be show as list if no index page.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago.I have following two lines in.htaccessfile and I just want to know what do they do.Options +FollowSymLinks Options +Indexes
What do the option FollowSymLinks and Indexes in .htaccess? [closed]
You cannot use aProxyPassin an htaccess file. The documentation says it is only applicable in the context:Context: server config, virtual host, directorywhich excludes htaccess (you can't have a<Directory>block in htaccess). However, youcanuse aProxyPassReverseto internally rewrite the Location field of proxied requests that cause a redirect. You'll just need to use mod_rewrite'sPflag to proxy instead ofProxyPass. So something like:RewriteEngine On RewriteRule ^/?img/(.*)$ http://internal.example.com/img/$1 [L,P] RewriteRule ^/?app/(.*)$ http://internal.example.com/app/$1 [L,P] ProxyPassReverse / http://internal.example.com/Just to be clear, you cannot useProxyPassorProxyPassReversein the htaccess file, but youcanuseProxyPassReversewith mod_rewrite rules that utilize thePflag.
I've never set up a proxy before. I'm using shared hosting, so to set Apache directives, I need to use .htaccess. Can I use .htaccess to do something like below? Any limitations?ProxyRequests Off ProxyPass /img/ http://internal.example.com/img/ ProxyPass /app/ http://internal.example.com/app/ ProxyPassReverse / http://internal.example.com/
Can ProxyPass and ProxyPassReverse work in htaccess?
^index\.php$ - [L]prevents requests forindex.phpfrom being rewritten, to avoid an unnecessary file system check. If the request is forindex.phpthe directive does nothing-and stops processing rules[L].This block is all one rule, and it says that if it is not a real file and not a real directory, reroute the request toindex.php.RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L]index.php itself interprets the URL that was requested by the client (PHP can see the requested URL using$_SERVER['REQUEST_URI']) and it calls the correct code for rendering the page the user requested.
This is the .htaccess code for permalinks in WordPress. I don't understand how this works. Can someone explain?<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule>I googled and found out that-fand-dpart means to give real directories and files higher priority.But then what are^index\.php$ - [L]andRewriteRule . /index.php [L]?How does WordPress process categories, tags, pages, and etc. with just this?Does it happen internally? If so, I'm interested in learning how to do it in PHP.Thanks
This is the .htaccess code in WordPress. Can someone explain how it works?
You can use this rule:RewriteRule ^menu\.php$ /new-page-name? [L,R=301]Take note of trailing?in the end which isused for stripping off any existing query stringin the original URI.
I've been struggling with some htaccess redirects. I just spent some time reading and searching on stack and couldn't get an anwser that works with my scenario.I'm in the process of making the 301 redirect for an old client website to a new one. The old pages has parameters query which I want to remove from the url./menu.php?idCategorie=29&idDetail=172to/new-website-page/I have multiple queries to do, here's a couple example:/menu.php?idCategorie=29&idDetail=172 /menu.php?idCategorie=29&idDetail=182 /menu.php?idCategorie=29&idDetail=184 /menu.php?idCategorie=29&idDetail=256Which all link to different new pages.Here's what I tried:RewriteCond %{QUERY_STRING} idDetail=172 RewriteRule ^menu.php(.*) /new-page/? [R=301,L]I get redirected correctly, but the URL keeps the query string:http://website.com/new-page/?idCategorie=29&idDetail=172I also tried this:RewriteRule ^menu.php?idCategorie=29&idDetail=172$ http://website.com/new-page/? [L,R=301]And this:RewriteCond %{QUERY_STRING} idDetail=172(.*)$ RewriteRule ^menu.php /new-page-name?$1 [L,R=301]And it didn't work (Still have the query string at the end)Thanks!
htaccess 301 redirect - Remove query string (QSA)
Let's assume you have this folder structure in your server.cpanel/ public_html/ public_ftp/ ..And the laravel folder structure isapp/ bootstrap/ public/ vendor/ composer.json artisan ..You can create a folder name mylaravelsite on your server inline withpublic_htmlandpublic_ftpfolder, and copy to it the whole laravel application except the public folder because you will paste all of it contents on thepublic_html, so you have now:.cpanel/ public_html/ public_html/packages public_html/vendor public_html/index.php public_html/.htaccess ... public_ftp/ mylaravelsite/ mylaravelsite/app mylaravelsite/bootstrap ...On yourpublic_html/index.phpchange the following line:require __DIR__.'/../bootstrap/autoload.php'; $app = require_once __DIR__.'/../bootstrap/start.php';torequire __DIR__.'/../mylaravelsite/bootstrap/autoload.php'; $app = require_once __DIR__.'/../mylaravelsite/bootstrap/start.php';and also don't forget to change/mylaravelsite/bootstrap/paths.phppublic path, you might use it.'public' => __DIR__.'/../public',to'public' => __DIR__.'/../../public_html',Your site should be running.
I was going through all possible sample on internet to solve this. Still it is an headache.I just want to avoid the 'public' inwww.mylaravelsite.com/public/and make it likewww.mylaravelsite.comfor the root directory.Now I do not want to avoid the security concern,So I learned.htaccesswould be the best way.Any solution friends ?& advance thanks for interacting !
Avoid public folder of laravel and open directly the root in web server
You should be able to do this using the combination of mod_env and theSatisfy anydirective. You can useSetEnvIfto check against theRequest_URI, even if it's not a physical path. You can then check if the variable is set in anAllowstatement. So either you need to log in with password, or theAllowlets you in without password:# Do the regex check against the URI here, if match, set the "require_auth" var SetEnvIf Request_URI ^/pretty/url require_auth=true # Auth stuff AuthUserFile /var/www/htpasswd AuthName "Password Protected" AuthType Basic # Setup a deny/allow Order Deny,Allow # Deny from everyone Deny from all # except if either of these are satisfied Satisfy any # 1. a valid authenticated user Require valid-user # or 2. the "require_auth" var is NOT set Allow from env=!require_auth
The site is on shared hosting. I need to password protect a single URL.http://www.example.com/pretty/urlObviously that's not a physical file path I'm trying to protect, it's just that particular URL.Any quick solution with .htaccess?
Password protect a specific URL
It's a simple two step processIn your .htaccess putAuthType Basic AuthName "restricted area" AuthUserFile /path/to/the/directory/you/are/protecting/.htpasswd require valid-userusehttp://www.htaccesstools.com/htpasswd-generator/or command line to generate password and put it in the .htpasswdNote 1: If you are using cPanel you should configure in the security section "Password Protect Directories"EDIT: If this didn't work then propably you need to do aAllowOverride Allto the directory of the .htaccess (or atleast to previous ones) inhttp.conffollowed by a apache restart<Directory /path/to/the/directory/of/htaccess> Options Indexes FollowSymLinks MultiViews AllowOverride All </Directory>
I am trying to password protect a subdomain and all of it's subdirectories and files, but my knowledge on the matter is very limited, how can I go about doing that?
Password protecting a directory and all of it's subfolders using .htaccess
It is possible to do this, but most likely your host implementedmod_securityfor a reason. Be sure they approve of you disabling it for your own site.That said, this should do it;<IfModule mod_security.c> SecFilterEngine Off SecFilterScanPOST Off </IfModule>
How can we disablemod_securityby using.htaccessfile on Apache server?I am using WordPress on my personal domain and posting a post which content has some code block and as per my hosting provider saidmod_securitygives an error and my IP has gone into firewall because ofmod_security.So I want to disablemod_securityby using.htaccessfile.
How can I disable mod_security in .htaccess file?
This is about Apache content negotiation.AMultiViewssearch is where the server does an implicit filename pattern match, and choose from amongst the results.For example, if you have a file calledconfiguration.php(or other extension) in root folder and you set up a rule in your htaccess for a virtual folder calledconfiguration/then you'll have a problem with your rule because the server will chooseconfiguration.phpautomatically (ifMultiViewsis enabled, which is the case most of the time).If you want to disable that behaviour, you simply have to add this in your htaccessOptions -MultiViewsThis way, your rule will be now evaluated because content negotiation is disabled.EditOn some shared hostings, thenegotiationmodule might not be enabled. That would give you then a 500 error. To avoid this error, you can, by default, encapsulate the directive in anIfModuleblock.<IfModule mod_negotiation.c> Options -MultiViews </IfModule>
I've been struggling a lot with an access rule that needed to rewrite one piece of URL adding a path.RewriteRule ^(configuration/.+)$ application-server/$1 [L,NC,R=301,NE]This Rule caused just a blank page on my Joomla site with no error log or messages. The curious thing is that all other rules I had worked perfectly:RewriteRule ^(log/.+)$ application-server/$1 [L,NC,R=301,NE] RewriteRule ^(monitor/.+)$ application-server/$1 [L,NC,R=301,NE]in the end, I've found in a forum a suggestion to use the following option:Options -MultiviewsThat actually solved the issue, however I wonder if there can be any side effects on other Rules when using this option.
What exactly does the Multiviews options in .htaccess?
There are two solutions:1. Using .htaccess with mod_rewriteRewriteEngine on RewriteCond %{REQUEST_URI} !^public RewriteRule ^(.*)$ public/$1 [L]2. You can add a index.php file containing the following code and put it under your root Laravel folder (public_html folder).<?php header('Location: public/');
I have a classic Larevel 5 project structure and I need to redirect all requests topublic/.I am on a classic hosting environment sopublic/is a subfolder of my document root.I shall imagine it can be done via .htaccess but I still need to figure out how. Anyone can help?Thanks
How do you redirect all request to public/ folder in laravel 5
Fromhttp://www.webconfs.com/how-to-redirect-a-webpage.phpI'd say you can use the following configurationDon't redirect subfolders/files (as you wanted): www.example.com/demo/ -> www.newexampledomain.comOptions +FollowSymLinks RewriteEngine on RewriteRule (.*) http://www.newdomain.com/ [R=301,L]Redirect to subfolders/files: www.example.com/demo/ -> www.newexampledomain.com/demo/Options +FollowSymLinks RewriteEngine on RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]
I have a domain that's not to be used anymore. I want to redirect all fromhttp://www.old.com/tohttp://www.new.com/, no matter what page the user's attempted to access onwww.old.com.Doing this:RewriteEngine on Redirect 301 / http://www.new.com/is fine for the root, but other pages would do this:http://www.old.com/cms -> http://www.new.com/cmswhereas I'd want it to go to the root, no matter what.
Redirect all traffic to root of another domain
Order Allow,Deny <FilesMatch "^toon\.php$"> Allow from all </FilesMatch>That is probably the most efficient that you can get.
How can I deny access to a complete folder and sub-folders, with the exception of one file? That file is: toon.php and resides in the same folder.
.htaccess deny access to all except to one file
That is not possible. You need to have aErrorDocumentdirective for each status code you want to handle differently than with the default error handler.
Is there something like a wildcard directive to catch all possible errors and deal with them in a single custom error page?ErrorDocument 404 /error.php?code=404 ErrorDocument 403 /error.php?code=403 ... ErrorDocument NNN /error.php?code=NNN #possible use of RegExp?I know I probably won't be dealing with a lot of custom error pages here, but I'm curious about this.
Single ErrorDocument directive to catch all errors (.htaccess)
try something like<IfModule mod_expires.c> ExpiresActive On ExpiresDefault "access plus 1 seconds" ExpiresByType text/html "access plus 1 seconds" ExpiresByType image/x-icon "access plus 2592000 seconds" ExpiresByType image/gif "access plus 2592000 seconds" ExpiresByType image/jpeg "access plus 2592000 seconds" ExpiresByType image/png "access plus 2592000 seconds" ExpiresByType text/css "access plus 604800 seconds" ExpiresByType text/javascript "access plus 86400 seconds" ExpiresByType application/x-javascript "access plus 86400 seconds" </IfModule>or<FilesMatch "\.(?i:gif|jpe?g|png|ico|css|js|swf)$"> <IfModule mod_headers.c> Header set Cache-Control "max-age=172800, public, must-revalidate" </IfModule> </FilesMatch>
I am trying to create a htaccess file for my website and the pageSpeed insights has shown that there are images and one css file without expiration.I am not sure where to start with this or how to do it, I have this code from a tutorial online and was wondering if this would be enough to work.<IfModule mod_expires.c> ExpiresActive On ############################################ ## Add default Expires header ## http://developer.yahoo.com/performance/rules.html#expires <FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$"> ExpiresDefault "access plus 1 year" </FilesMatch> </IfModule>Or does this code do what I need it to do?Thanks
htaccess leverage browser caching for images and css
It's not part of PHP; it's part of Apache.http://httpd.apache.org/docs/2.2/howto/htaccess.html.htaccess files provide a way to make configuration changes on a per-directory basis.Essentially, it allows you to take directives that would normally be put in Apache's main configuration files, and put them in a directory-specific configuration file instead. They're mostly used in cases where you don't have access to the main configuration files (e.g. a shared host).
I am a beginner to Zend framework and I want to know more about the.htaccess file and its uses. Can somebody help me?I found an example like this:.htacess fileAuthName "Member's Area Name" AuthUserFile /path/to/password/file/.htpasswd AuthType Basic require valid-user ErrorDocument 401 /error_pages/401.html AddHandler server-parsed .html
What is .htaccess file?
Fromhttp://httpd.apache.org/docs/current/mod/mod_rewrite.htmlornext|OR(or next condition) Use this to combine rule conditions with a local OR instead of the implicit AND. Typical example:RewriteCond %{REMOTE_HOST} ^host1 [OR] RewriteCond %{REMOTE_HOST} ^host2 [OR] RewriteCond %{REMOTE_HOST} ^host3 RewriteRule ...some special stuff for any of these hosts...
Just found this .htaccess rewrite codeRewriteEngine on RewriteCond %{HTTP_HOST} ^my.domain.com$ [NC,OR] RewriteCond %{REQUEST_URI} !public/ RewriteRule (.*) /public/$1 [L]And I was wondering what was the purpose of the "OR" flag. Already checked the dochttp://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewriteflagsbut coulnd find any infos.Any ideas?
"OR" Flag in .htaccess mod_rewrite
It is probably not the best thing to do. You need to at least check out your PHP error log for things going wrong ;)# PHP error handling for development servers php_flag display_startup_errors off php_flag display_errors off php_flag html_errors off php_flag log_errors on php_flag ignore_repeated_errors off php_flag ignore_repeated_source off php_flag report_memleaks on php_flag track_errors on php_value docref_root 0 php_value docref_ext 0 php_value error_log /home/path/public_html/domain/PHP_errors.log php_value error_reporting -1 php_value log_errors_max_len 0
I just want to only turn on PHP errors and disable all notices and warnings in PHP files.
How can I disable notices and warnings in PHP within the .htaccess file?
Just add aFilesMatchorFilesdirective to limit it to a specific script.The following would block acces to all scripts ending in "admin.php" :<FilesMatch "admin\.php$"> Order deny,allow Deny from all Allow from 10.0.0.0/24 </FilesMatch>The following would ONLY block admin.php :<Files "admin.php"> Order deny,allow Deny from all Allow from 10.0.0.0/24 </Files>For more information refer to the apache docs onConfiguration Sections.ShareFolloweditedFeb 18, 2011 at 15:21answeredFeb 18, 2011 at 15:13wimvdswimvds12.8k22 gold badges4141 silver badges4242 bronze badgesAdd a comment|
How to allow access to file only to users with ip which are in a range of ip addresses?For example file admin.php. and range from 0.0.0.0 to 1.2.3.4.I need configure access to only ONE file not to directory.
htaccess access to file by ip range
In your.htaccessyou can add:PHP 5.x<IfModule mod_php5.c> php_value memory_limit 64M </IfModule>PHP 7.x<IfModule mod_php7.c> php_value memory_limit 64M </IfModule>If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.Read more onhttp://support.tigertech.net/php-valueShareFolloweditedOct 19, 2018 at 12:56CommunityBot111 silver badgeansweredAug 29, 2012 at 7:27Ivan HušnjakIvan Hušnjak3,49333 gold badges2222 silver badges3030 bronze badges44If you are using PHP 7, then the code should look like this:<IfModule mod_php7.c> php_value memory_limit 900M </IfModule>–Carol-Theodor PeluOct 8, 2018 at 7:241@Carol-Theodor Pelu . I did not understand why 900M ?–MindRoasterMirMar 8, 2019 at 20:291@MindRoasterMir its not about 900M, it was about usingmod_php7.cfor PHP7... answer is already edited, so this comment now looks odd.–Ivan HušnjakMar 11, 2019 at 17:36just found this, but I don't see the difference between the two statements. although it could be my old eyes. What am I missing (I get that the ifModule statements are an example of how to check versions.)–Rick HellewellApr 11, 2019 at 1:38Add a comment|
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed11 years ago.Improve this questionI am working on WordPress. I need to increase the memory, so I added the following line to my .htaccess file# 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> php_value memory_limit 64Mmy sample php page<?php phpinfo();but it throws the 500 internal server error. what is the problem here..
Set Memory Limit in htaccess [closed]
The Indexes option sets whether you can "browse" the directory or not. If indexes is set to plus, and the directory has no index.html or index.php (of whatever) file, it will show the contents of the directory just like your filemanager would do. So if there are ten images in there, it simply shows them as a list with links to the actual image. You can click them and open them.Most of the time this is not what you want. You don't want others to see what is inside that folder. So then you turn it off with -Indexes.Here you can see an example of an open dir, as they are called:http://www.ecoutetpartage.fr/images/ShareFollowansweredApr 5, 2013 at 15:43SPRBRNSPRBRN2,43644 gold badges3636 silver badges4848 bronze badges0Add a comment|
I looked at the explanation in the apache.org site but it didn’t explained in a way I can understand. I found some info here.htaccess File Options -Indexes on Subdirectoriesbut it doesn’t explain it either.
What is the htaccess Options -Indexes for?
You can't include rules, statements, definitions, or directives from other files from an htaccess file. TheIncludedirective can't be used inside an htaccess file. Part of the point of an htaccess file is to act similarly to a<Directory>block but be self contained and unable to access things outside of the directory itself (subdirectories are ok) but more specifically nothing outside of the document root. This way, someone doing malicious things won't be able to point requests or include files/content from other directories by hacking the htaccess file.In the scope of mod_rewrite specifically, there are options for theRewriteOptionsthat allowinheriting rewrite rules from the htaccess file from a parent directory, but nothing to arbitrarily include rules from anywhere.ShareFollowansweredNov 30, 2012 at 7:32Jon LinJon Lin143k2929 gold badges221221 silver badges220220 bronze badges0Add a comment|
Is it possible to do include rules from another htaccess file in .htaccess ?.htaccess RewriteEngine On RewriteCond ... RewriteRule ... Include .htaccess1 . . Include .htaccess2Doing this gives a 500. Include not allowed here Is there a way to do this ? Because I need this pretty badly.
Include another htaccess file from .htaccess
You need to append with the [QSA] (query string append) tag. TryRewriteEngine on RewriteRule ^([a-z]{2,2})/([a-zA-Z0-9_-]+)$ index.php?lang=$1&page=$2 [QSA]Seehttp://httpd.apache.org/docs/2.2/mod/mod_rewrite.htmlShareFollowansweredNov 1, 2010 at 17:04SimonSimon5,21688 gold badges4343 silver badges6565 bronze badges34Thank you very much. That worked. It's funny how simple the solution is after some of the things I tried...–EnkayNov 1, 2010 at 17:092It doesn't seem to work on mine, even with the QSA tag. The correct page displays, but because the $_GET seems unobtainable, it throws loads of errors. I'm usingRewriteRule ^details/([^/])/?$ details?Pin=$1 [QSA]–LeeDec 4, 2014 at 9:37You sir are a legend :)–Fadi ObajiDec 28, 2017 at 20:16Add a comment|
I'm having issues keeping the parameters of the URL working after an.htaccessURL rewrite.My.htaccessrewrite is as follows:RewriteEngine on RewriteRule ^([a-z]{2,2})/([a-zA-Z0-9_-]+)$ index.php?lang=$1&page=$2Which means:example.com/index.php?lang=en&page=productdisplays asexample.com/en/productFor some reason, when I add a?model=AB123&color=somethingat the end of my URLs I am not able to retrieve those parameters in PHP using$_GET['model']and$_GET['color']even though they are present in the displayed URL.Why aren't the variables passed along?
.htaccess RewriteRule to preserve GET URL parameters
You could use:Order Allow,Deny Deny from 66.249.74.0/24 Allow from allOr you could use this:RewriteEngine on RewriteCond %{REMOTE_ADDR} ^66\.249\.74\. RewriteRule ^ - [F]ShareFolloweditedAug 28, 2013 at 8:52answeredAug 28, 2013 at 8:43PrixPrix19.5k1616 gold badges7575 silver badges134134 bronze badges9I want to tell you that , I use Common100 Online chat software for detect who visiting on my website page , and i always found this IP address visit 66.249.74.* . Please see the image !laroute-angkor.com/IP.jpgSo what should i do ?–Msy MarinaAug 28, 2013 at 8:59@MsyMarina that IP is from googlewhois.arin.net/rest/net/NET-66-249-64-0-1/pft–PrixAug 28, 2013 at 9:00Sorry, I don't knowwhois.arin.net/rest/net/NET-66-249-64-0-1/pftBut i don't want see those IP access on my website .–Msy MarinaAug 28, 2013 at 9:071@MsyMarina that site I have sent above is a trusted site that tracks the owners of each IP block, it says those IP's are from google so yes you have nothing to fear.–PrixAug 28, 2013 at 9:201@JBeckyou can read about it in this link, scroll down to IPv4–PrixDec 18, 2017 at 21:16|Show4more comments
I have detected that a range of IP addresses may be used in a malicious way and I don't know how to block it.I would like to block the range 66.249.74.* from accessing my website by using the .htaccess file.
How to Block an IP address range using the .htaccess file
RewriteCondis already your "if-condition". Just add another one:RewriteCond %{HTTP_HOST} !=localhost RewriteCond %{HTTP_HOST} !^www\. RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]ShareFollowansweredApr 19, 2012 at 15:27LazyOneLazyOne162k4646 gold badges401401 silver badges404404 bronze badges45Or use RewriteCond %{REMOTE_ADDR} !127.0.0.1 as an alternative.–JanApr 19, 2012 at 18:237RewriteCond %{REMOTE_ADDR} !=127.0.0.1 to be exact!–GeorgeMar 4, 2014 at 15:594If IPv6 is enabled, localhost may resolve to::1, so you might want to add this:RewriteCond %{REMOTE_ADDR} !=::1–Andreas LeyMay 13, 2014 at 12:161Why can't I use space here?!= localhost–Jens TörnellMar 26, 2018 at 13:22Add a comment|
I have the following in my htaccess to force the www in URLs:RewriteCond %{HTTP_HOST} !^www\. RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]How do I only apply this if not on localhost? Is there some sort of if-condition I can put? Right now, I'm getting something like this:http://www.localhost/...
Apache mod_rewrite: force www only if not in localhost
You can use the Apache"Satisfy"directive.Here is an example of using it :AuthType Basic AuthName "Please Log In" AuthUserFile /some/path/.htpasswd Require valid-user Order deny,allow Deny from all Allow from 127.0.0.1 Satisfy anyAccess without password is only allowed from 127.0.0.1.Hope this helps.ShareFollowansweredOct 11, 2011 at 18:18FbnFgcFbnFgc1,6661616 silver badges1919 bronze badges2+1 this is exactly what I do. Moreover, if you want to disable checks in some directory (e.g. some public/), just place in subdir's.htaccess:–pwesOct 12, 2011 at 16:57Allow from allandSatisfy any–pwesOct 12, 2011 at 17:00Add a comment|
So I want to restrict access to a url. Now if they are coming from a given IP address then they shouldn't be prompted for a password. If they are not coming from a givin IP address then they should be prompted for a password.so a either or of:AuthUserFile /some/path/.htpasswd AuthName "Please Log In" AuthType Basic require valid-userand:order deny,allow deny from all allow from x.x.x.x
htaccess - using password OR ip whitelist
RewriteRule ^(.*)([^/])$ http://%{HTTP_HOST}/$1$2/ [L,R=301]Edit: in the case you want to exclude some requests like for php files:RewriteCond %{REQUEST_URI} !\.(php|html?|jpg|gif)$ RewriteRule ^(.*)([^/])$ http://%{HTTP_HOST}/$1$2/ [L,R=301]ShareFolloweditedOct 16, 2011 at 1:01answeredOct 15, 2011 at 23:20undoneundone7,85744 gold badges4545 silver badges7171 bronze badges31You may also want to include css and js. This is very useful!–EruantMar 12, 2013 at 12:40@undone Might I ask what the?after html stands for, and why you didn't putphp?with the question mark?–Daniel W.Feb 14, 2014 at 14:2110@DanFromGermany question mark in regexp indicates that preceding character (in this casel) , may or may not exists in the string. so in can cover bothhtmandhtmlextensions!–undoneFeb 14, 2014 at 20:10Add a comment|
I have the following code in my htaccess file:# Force Trailing Slash RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^[^/]+$ %{REQUEST_URI}/ [L,R=301]That seems to work fine when I go towww.mydomain.com/testit redirects it to /test/. The problem is when I go towww.mydomain.com/test/anotherit doesn't put the trailing slash on another.Does anyone know how to modify my code to make the trailing slash work no matter how long the URL is?Thanks!
.htaccess Rewrite to Force Trailing Slash at the end
You probably want the%{REMOTE_ADDR}to match against, but you can't use CIDR notation as the%{REMOTE_ADDR}isliterally the remote addressand you can use a regular expression to try to match against it. So for 123.45.67.89/28, (123.45.67.80 - 123.45.67.95), you'd have to do something like this:RewriteCond %{REMOTE_ADDR} !^123\.45\.67\.8[0-9]$ RewriteCond %{REMOTE_ADDR} !^123\.45\.67\.9[0-5]$ShareFollowansweredJul 25, 2012 at 16:53Jon LinJon Lin143k2929 gold badges221221 silver badges220220 bronze badges32If you want to match a wider range - e.g., indeterminate third and fourth octets - you could do!^123\.45\.[0-9]{1,3}\.[0-9]{1,3}$-- this will match any number from 0-255 in the third and fourth octets but let you define the first half of the IP. Recently had to do this on a WordPress I was developing, to allow WordPress JetPack servers to connect in to the XML-RPC endpoint while still redirecting regular visitors to a separate site.–Chris WoodsJan 17, 2019 at 2:33Very inefficientRewriteCond,@zts answer is way better–Pedro LobitoMay 12, 2020 at 0:26This was answered when Apache 2.2 was widely used, now everything's 2.4 so using the expr is way better–Jon LinJun 12, 2020 at 14:57Add a comment|
Currently I am redirecting all users except for the IP 12.345.678.90 using:RewriteEngine On RewriteCond %{REQUEST_URI} !/maintenance$ RewriteCond %{REMOTE_HOST} !^12\.345\.678\.90 RewriteRule $ /maintenance [R=302,L]What syntax would I use to allow a range? In my Allow list I have:Allow from 123.45.678.90/28Would it work if I just update the REMOTE_HOST line to:RewriteCond %{REMOTE_HOST} !^12\.345\.678\.90/28
Redirect a range of IPs using RewriteCond
Simple add a^to beginning and a$to the end^tells tells the regex to match the beginning of the url$tells tells the regex to match the end of the urlredirectMatch 301 ^/user$ http://clients.mydomain.comSo now your rule will only match/userand not/some/useror/user/nameor/some/user/nameNOTE:If you want to match/user/and/userthen use^/user/?$?says to match the previous character/group zero to one timesShareFolloweditedNov 21, 2011 at 19:42answeredNov 21, 2011 at 19:36Jeff WilbertJeff Wilbert4,43011 gold badge2121 silver badges3535 bronze badges22Checking for the trailing / is a good idea. Firefox hides it so even though you think the url is /user it's actually being passed as /user/–SomethingOnDec 19, 2013 at 19:49But what if you have space characters `? You need double quotes to handle those properly. using escapes\ ` in the regex ofRedirectresults in the system thinking it's an extra parameters, rather than an escaped space. And if you have double quotes, you can't use^or$to specify exact matches–ahnbizcadSep 14, 2016 at 1:11Add a comment|
I'm trying to redirect with apache .htaccess. I have the following codesredirectMatch 301 /user http://clients.mydomain.comit works pretty well, but I don't want"/user/login"to be directed to"http://clients.mydomain.com/login".How do I prevent it?
How to redirect only when exact url matches?
minimum configuration for your .htaccess to work:AllowOverride FileInfo Optionsallowing all configuration will work as well:AllowOverride AllShareFollowansweredAug 9, 2011 at 14:35Jacek KaniukJacek Kaniuk5,2292626 silver badges2828 bronze badges41AllowOverride All wroked but AllowOverride FileInfo Options doesn't, wp-includes/.htaccess: deny not allowed here–SérgioJun 7, 2016 at 18:42@Jacek Kaniuk How to allow htaccess in 1and1–Ilyas karimOct 17, 2016 at 12:093AllowOverridecontrols thetypeof directives that can be used in.htaccess. So whetherAllowOverride FileInfo Optionsis sufficient is entirely dependent on what directives you are using.FileInfois required for mod_rewrite,FileInfo Optionsis required for the.htaccessfile in the question. To useDenyin.htaccessyou also need to include theLimitdirective-type. @Sérgio But most just stick withAllfor "ease of use".–MrWhiteApr 6, 2018 at 0:382However, contrary to what this answer implies, you should never set anything other thanAllowOverride Nonein the<Directory />container (as stated in the question) - which refers to theserver root- theApache docsspecifically warn against doing this "for security and performance reasons". Instead, this should be set for the specific directory that contains the.htaccessfile, such as the DOCUMENT_ROOT, as mentioned in @anubhava's answer.–MrWhiteApr 6, 2018 at 0:44Add a comment|
I uploaded the .htaccess to the server and received anError 500 (Internal Server Error).And in the error log I had the following error:.../.htaccess: RewriteEngine not allowed hereButmod_rewrite.sois enabled.So, do I need to change<Directory /> Options FollowSymLinks AllowOverride None </Directory>to<Directory /> Options FollowSymLinks AllowOverride All </Directory>in the/etc/httpd/conf/httpd.conffile?Or could it be something else? The .htaccess file should be okay, because it works perfectly fine on my localhost. I just don't want to screw anything up.Here's part of my .htaccess file:Options All -Indexes Options +FollowSymLinks RewriteEngine On
.htaccess: RewriteEngine not allowed here
.(dot) files are hidden by default on Unix/Linux systems. Most likely, if you know they are.htaccessfiles, then they are probably in the root folder for the website.If you are using a command line (terminal) to access, then they will only show up if you use:ls -aIf you are using a GUI application, look for a setting to "show hidden files" or something similar.If you still have no luck, and you are on a terminal, you can execute these commands to search the whole system (may take some time):cd / find . -name ".htaccess"This will list out any files it finds with that name.ShareFollowansweredAug 4, 2011 at 6:26OverZealousOverZealous39.5k1515 gold badges9898 silver badges101101 bronze badges1ahh. Got it. I assumed that be seeing the *.htpasswd files, I was seeing the .dot files, but actually since they had the subdomain in front, they were not actually .dot files.–James John McGuire 'Jahmic'Aug 4, 2011 at 6:33Add a comment|
I may need to modify our .htaccess file. Problem is I can't find it. We have several subdomains along side each other in the vhosts directory, and each subdomain has an associated .htpasswd file. How can find where the .htaccess file is.Obviously, I didn't set this up and I'm certainly not known as an unix admin expert.
.htaccess: where is located when not in www base dir
You could do it with mod_rewriteOptions +FollowSymlinks RewriteEngine on RewriteCond %{REMOTE_ADDR} !=123.45.67.89 RewriteRule index.php$ /construction.php [R=301,L]ShareFolloweditedOct 11, 2012 at 12:44Linus Kleen34.2k1111 gold badges9494 silver badges9999 bronze badgesansweredJan 24, 2012 at 10:52kufikufi2,4381919 silver badges1414 bronze badges42What about adding IP's, like a list of IPs?–Ben RacicotApr 18, 2014 at 23:09@BenRacicot: Try something like this:stackoverflow.com/questions/11653461/…–kufiMay 28, 2014 at 6:50What about a background image on construction.php? That would be redirected as well, how to fix that?–riseagainstJun 30, 2014 at 16:3112 notes: this will only redirect requests to "index.php" not to any other files and you may also need to include conditions to not redirect for any files you reference in the construction page. Thus @linuskleen's answer works betterstackoverflow.com/a/8985628/5441–Darryl HeinNov 14, 2015 at 19:22Add a comment|
Basically, I am trying to work on the front end of a website, but I would like everyone else but myself to be redirected to a construction page if you like. I currently have:redirect 301 /index.php http://www.domain.com/construction.phpWhile this works, it works to well, I would like to be able to still see the live site myself, is it possible to exclude everyone but my IP?Thanks again.
.htaccess redirect to all IP's but mine
You need to add the[QSA]flag("query string append")RewriteRule ^apps/([A-Za-z0-9-_]+)/?$ index.php&app=$1 [L,QSA]For page 301 redirects with the[R]flag as opposed to internal rewrites like this one, the query string is automatically appended. However, you must force it with[QSA]for the internal rewrite.ShareFollowansweredOct 13, 2012 at 12:40Michael BerkowskiMichael Berkowski269k4646 gold badges445445 silver badges391391 bronze badges4Thanks, I didn't realise it was that simple.–Daniel OakeyOct 13, 2012 at 12:421+1 Agree with @DanielOakey.. I was trying to hack something with regex and it wasnt working..–Karthik TMar 16, 2014 at 13:592To clarify, it's not about rewrites vs redirects.httpd.apache.org/docs/current/rewrite/flags.html#flag_qsasays: When the replacement URI contains a query string, the default behavior of RewriteRule is to discard the existing query string, and replace it with the newly generated one. Using the [QSA] flag causes the query strings to be combined.–Denis HoweNov 8, 2016 at 11:242Maybe you guys already know, but make sure to leave NO SPACE beforeQSA. That's gonna end up in a HTTP 500...–Romeo SierraSep 13, 2021 at 3:11Add a comment|
I want to mod_rewrite a URL to another page, but then I also want any query strings added to be preserved.RewriteEngine On #enforce trailing slashes RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_URI} !# RewriteCond %{REQUEST_URI} !(.*)/$ RewriteRule ^(.*)$ http://localhost/siteroot/$1/ [L,R=301] RewriteRule ^apps/([A-Za-z0-9-_]+)/?$ index.php&app=$1So if a user visitsapps/app1/,index.php?app=app1is shown. However, I want to be able to preserve optional query strings, so that visitingapps/app1/?variable=xreturnsindex.php?app=app1&variable=x.What mod_rewrite rule/condition would make this happen?
How can I mod_rewrite and keep query strings?
By default,Redirectsort ofmapsthe path node to a new path node, so anything after the first path gets appended to the target URL.Try:RedirectMatch 301 ^/abc/cba/ http://www.aaa.com/?Or if you'd rather use mod_rewrite instead of mod_alias:RewriteEngine On RewriteRule ^/?abc/cba/ http://www.aaa.com/? [R=301,L]ShareFollowansweredJul 30, 2012 at 5:34Jon LinJon Lin143k2929 gold badges221221 silver badges220220 bronze badges26Just a hint: You should be really sure if you want to use301. Because it really can be a realpermanentredirect (stackoverflow.com/questions/9130422/…). If you are not sure and want to avoid trouble in future, use302. Anyway advantageous in the implementation and testing phase.–Martin SchneiderJun 5, 2018 at 21:04Does case mater? Would/abc/CBA/get redirected tohttp://www.aaa.com/?with the provided solution or do you need to account for casing options, too? Also, what does the?do for us?–HPWDAug 30, 2021 at 14:58Add a comment|
I'm trying to redirect a folder and all its sub files to a URL with a .htaccess file.ButRedirect 301 /abc/cba/ http://www.aaa.com/Will make/abc/cba/ddd/index.htmlredirect tohttp://www.aaa.com/ddd/index.htmlWhat I want is redirect/abc/cba/ /abc/cba/ddd/index.htmltohttp://www.aaa.com/Could anyone help? Thanks. If anything not clear, please let me know.
.htaccess redirect folder to a url
All you need is to add the following code to your root.htaccessfile:RewriteEngine on RewriteCond %{HTTP_HOST} !^www\. RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]ShareFolloweditedFeb 4, 2015 at 17:07CommunityBot111 silver badgeansweredJul 25, 2013 at 16:31Digital siteDigital site4,4271212 gold badges4949 silver badges7373 bronze badges69It would be nice if you explained to people what this actually does. Here's a blog using the same codedense13.com/blog/2008/02/27/…–trainoasisJul 16, 2014 at 7:29Thanks@trainoasis for the link. It should be self explanatory. it adds www to the domain and any subdomain or subfolders and so on...–Digital siteJul 16, 2014 at 15:064You need to understand regular expressions to decipher the code. The second line means: if the HTTP_HOST does not (!) start with (^) "www.", then put it in memory for the next line. The next line says: from what was captured in the previous line, match everything (.*) from beginning (^) to end ($) and save everything (inside the parenthesis) as $1. Then replace $1 with "www." plus the HTTP_HOST variable.–Damian GreenMar 12, 2015 at 18:011where to add these code tho? does it have to do with backend language?–MartianMartianAug 10, 2015 at 1:051I tried using this code but it does not work for me. I get forbidden error when i try to access my website without www.–node_sainiApr 13, 2017 at 8:09|Show1more comment
When I type in my domain name like without thewww(likehttp://example.com), it doesn't work and gives error message. However, when I add thewwwto it (likehttp://www.example.com), it works.Isn't it supposed to work both ways (with and without thewww)?
Domain doesn't work without `www`
Try this code :RewriteEngine on RewriteCond %{REQUEST_URI} !^/index.html$ RewriteCond %{REQUEST_URI} !\.(gif|jpe?g|png|css|js)$ RewriteRule .* /index.html [L,R=302]ShareFolloweditedJul 17, 2013 at 20:52answeredJul 17, 2013 at 20:26Lucas WillemsLucas Willems6,90544 gold badges2929 silver badges4747 bronze badges5Your second condition should escape the dot as well!\.(gif .... Otherwise this could stop a match on a directory ending with these characters. Consider using[NC]as well.–Ravi K ThapliyalJul 17, 2013 at 20:46Just what I tried to ask on webmaster. Thanks! I changed the 302 to 301 and was in business :) I now just need to also redirect all images not in a folder in the root. So /img/*gif|jpg|png should be left alone but /subfolderNotImg|Js|Css should redirect–mplungjanApr 11, 2014 at 4:45Actually it seems I should use 410 Gone instead of redirection–mplungjanApr 11, 2014 at 13:23You might want to add svg|map|woff2|woff|ttf. For loading svg images, map files and webfonts.–FlorisMay 6, 2019 at 9:14Could you provide an universal solution that would work with apache alias? actuallywww.example.com/projects/awesome.htmlredirects towww.example.com/index.htmlinstead ofwww.example.com/projects/index.html–BellashJun 8, 2022 at 19:25Add a comment|
How to redirect all pages (pages only) to index.html using htaccess file and not redirect the image files. For some reason I am using this code and an image file on the index.html page isn't showing up.RewriteEngine on RewriteCond %{REQUEST_URI} !^/index.html$ RewriteRule .* /index.html [L,R=302]
How to redirect all pages only to index.html using htaccess file and not redirect the image files
Having[NC]is definitely not mandatory but it is recommended to have it for matching domains. Modern browsers might be converting domain names to lowercase but what about old browsers and command line utils likewget,curletc, so you should not always rely on clients sending you lowercase domain name and keep[NC].About your 2nd question.matchesany charactertherefore it is able to matchwww.domain.combut it will also matchwww-domain-comtext which you don't want to match. So it is better to havewww\.domain\.comShareFollowansweredApr 7, 2011 at 14:10anubhavaanubhava771k6666 gold badges582582 silver badges649649 bronze badges2Thanks. I suppose the 2nd one always worked because it's applied to just a domain, so if osmeone enetered www-domain-com would not even reach the domain at all.–Marco DemaioApr 7, 2011 at 14:24btw do you have an idea on how to answer to this questionstackoverflow.com/questions/5279470/…–Marco DemaioApr 7, 2011 at 14:41Add a comment|
I have seen many times inhtaccessthese type of rules :RewriteCond %{HTTP_REFERER} !^http://www.domain.it$ [NC]orRewriteCond %{HTTP_HOST} !^www\.domain\.it$ [NC]Why is theNCflag necessary, when checking only the domain part?I noticedbrowsers always converts uppercases in domain names into lower cases, so I don't see what the[NC]flag is usueful for in this case.I mean if we check the remaining part of the url I understand the need for[NC]flag cause on Unix systemswww.domain.com/index.htmlis different file thanwww.domain.com/INDEX.HTMLbut I don't understand the need ofNCflag when we check only the domain part in the RewriteRule.Since you took the time to read the above,let me ask also one minor questionnot directly related toNCflag, but still related toRewriteCondBothRewriteCondshown above work well, I thought only the one with slash before dots would work (!^www\.domain\.it$) becausethe dot without a slash should mean'any char'in regexp whilest the\.means the dot char, but surpraisingly also the other one works well, do you know why?
mod_rewrite RewriteCond - is NC flag necessary for just domain part? And some more
I actually ended up finding the answer on ServerFault:https://serverfault.com/questions/32513/url-redirect-to-another-page-on-the-same-site"This example will 302 redirect all URLs to "/underconstruction.html":RewriteEngine On RewriteCond %{REQUEST_URI} !=/underconstruction.html RewriteRule ^ /underconstruction.html [R=302](which translates as "If URI is not /underconstruction.html, redirect to /underconstruction.html")" - TommehShareFolloweditedApr 13, 2017 at 12:13CommunityBot111 silver badgeansweredAug 21, 2009 at 23:58barfoonbarfoon27.8k2626 gold badges9393 silver badges138138 bronze badges22If this does not work at first, try changing the apache.conf (on linux: /etc/httpd/conf/httpd.conf ) settingAllowOverride NonetoAllowOverride Allinside the<Directory "/var/www/html">configuration. Then restart apache ( on linux: /etc/init.d/httpd restart )–T. Brian JonesSep 27, 2011 at 10:151This breaks images or css files etc. as all assets are being repointed to the html file.–BSUKJul 4, 2022 at 22:27Add a comment|
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed14 years ago.Improve this questionI am trying to redirect ALL requests for mydomain.com whether they are something like:http://www.mydomain.comhttp://mydomain.comhttp://mydomain.com/photoshttp://mydomain.com/index.php?id=672to be redirected tohttp://mydomain.com/index.htmlAs long as it has mydomain.com in it, they should see this page - its a we'll be back soon message.Should I do it in .htaccess or conf? How?
Redirect ALL requests under a domain to static page [closed]
That's a bit simpler.RewriteEngine On RewriteCond %{HTTPS} off [OR] RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC] RewriteRule ^(.*)$ https://www.domain.com/$1 [L,R=301]ShareFollowansweredMay 2, 2016 at 15:50AleyAley8,58077 gold badges4444 silver badges5757 bronze badges7could you please explain the conditions as well? I am bit novice here.–SamJan 7, 2017 at 12:391Line 2 checks if HTTPS is off then we have an OR condition with line 3. Line 3 checks if hostname is different from www.domain.com. If one of them gives true, last line takes action and redirects "R=301" with HTTP Code 301 todomain.com–AleyJan 7, 2017 at 16:511By this all the subdomains gets redirected as well. for eg.api.domain.comchanges towww.domain.com.. is there any way to addwwwonly to rootdomain.comand not any subdomain.–SamJan 9, 2017 at 11:441this will not redirecthttps://example.comtohttps://www.example.com–Ramesh-XJan 10, 2019 at 5:11dont think that works for subfolders if you have another .htaccess on them–Bruno SimoesFeb 2, 2019 at 9:53|Show2more comments
I would like to know if this code in.htaccessfor forcing SSL and WWW in URL is correct, because with another codes I usually get redirect loop, e.g.RewriteCond %{HTTPS} !=onand now it works like a charm (suspiciously). Also, is possible to write it better/simplier?# Force to SSL RewriteCond %{HTTP:HTTPS} !1 RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L] # Force to WWW RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC] RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
Forcing SSL and WWW using .htaccess
You will need to know something about the URLs, like do they have a specific directory or some query string element because you have to match for something. Otherwise you will have to redirect on the 404. If this is what is required then do something like this in your .htaccess:ErrorDocument 404 /index.phpAn error page redirect must be relative to root so you cannot use www.mydomain.com.If you have a pattern to match too then use 301 instead of 302 because 301 is permanent and 302 is temporary. A 301 will get the old URLs removed from the search engines and the 302 will not.Mod Rewrite Reference:http://httpd.apache.org/docs/1.3/mod/mod_rewrite.htmlShareFollowansweredMar 2, 2010 at 14:33Todd MosesTodd Moses11k1111 gold badges4747 silver badges6565 bronze badges19Minus as this is not a redirect–TheBlackBenzKidSep 3, 2015 at 9:40Add a comment|
I couldn't find a straight answer to my question and need to know it from the real experts.I had a website which urls were generated by Joomla. I believe that tons of urls are around in the search engines and I really don't know which of them all. A 302 redirect would be an option, but I can't say which urls need to be redirected.The only thing I know that all the urls were generated by a sef404 script, it's a SEO script for Joomla.My question, how can I make sure that all the orphan urls on google and other search engines are delivered correctly with a .htaccess file?How do I 301 redirect all 404 pages to the homepage (root document)At the moment I use a custom 404.html error file, but there are too many files and will give a rollercoaster of custom 404 error pages
Redirecting 404 error with .htaccess via 301 for SEO etc
Download the geoPlugin class from:http://www.geoplugin.com/_media/webservices/geoplugin.class.phps(free lookup limit of 120 requests per minute and block for 1h if crossed the limit. the block will automatically remove 1 hour after the last time your server stopped sending more than 120 requests a minute)Put aindex.phpfile in your root folder:<?php require_once('geoplugin.class.php'); $geoplugin = new geoPlugin(); $geoplugin->locate(); // create a variable for the country code $var_country_code = $geoplugin->countryCode; // redirect based on country code: if ($var_country_code == "AL") { header('Location: http://sq.wikipedia.org/'); } else if ($var_country_code == "NL") { header('Location: http://nl.wikipedia.org/'); } else { header('Location: http://en.wikipedia.org/'); } ?>Here is a list of country codes:http://www.geoplugin.com/iso3166ShareFolloweditedDec 23, 2020 at 15:48Vikas Kumar322 bronze badgesansweredJul 30, 2014 at 13:26Porta ShqipePorta Shqipe86688 silver badges88 bronze badges11Correct me if i am wrong, but using this plugin, site become so slow becuase of this API call, we have dropped using this one.–Dheeraj ThedijjeOct 23, 2018 at 12:13Add a comment|
I made a site it with some subdomains; according to the country's IP address the user is supposed to be automatically redirected to corresponding subdomain.Example :Main site isabcd.comSuppose some one fromIndiatyped this url abcd.com,then the page redirects toind.abcd.com
how to redirect domain according to country IP address
Place general rules in:/.htaccessPlace /admin/ specific rules in:/admin/.htaccessPlace /admin/tool/ specific rules in:/admin/tool/.htaccessShareFollowansweredJan 20, 2010 at 17:42Alix AxelAlix Axel153k9797 gold badges396396 silver badges501501 bronze badges3does this mean if I want to change the max upload size for a tool in /admin .. do I need to put it in a .htaccess file in /admin? Probably I'd want to use the same settings for /user/tool as well. so do I have to keep different files? many thanks for reply–user187580Jan 20, 2010 at 18:21Yes, you can apply a max upload size for the entire site in/.htaccessof 2MB and increase it to 8MB in the admin area/admin/.htaccessand even further increase it to 32MB in the admin/tool area/admin/tool/.htaccess... You get the point. =)–Alix AxelJan 20, 2010 at 18:30this is called .. I want to make my cake a little sweet, or more sweeter.. or may be sweetest.. what should i add... and answer is : add sugar :D .. thanks +10–MFarooqiAug 21, 2017 at 18:54Add a comment|
I have some settings which I want to use in .htaccess file. The settings are for some functionality at/admin/toolfolder level .. but I want to include some settings for/adminand/locations as well.My question is what is the best location to put this file at??ThanksUpdateJust fyi .. I want to apply settings likemax file upload size maz execution time etc
Where to put .htaccess file?
Try adding a condition like:RewriteCond %{HTTPS} off [OR] RewriteCond %{HTTPS}:s on:(s)Which checks that either HTTPS is off or it's on and you can use a backreference to fetch the "s" character:RewriteCond %{HTTP_HOST} ^sub.domain.com$ [NC] RewriteCond %{HTTPS} off [OR] RewriteCond %{HTTPS}:s on:(s) RewriteRule ^ http%1://sub.domain.com:2368%{REQUEST_URI} [P,QSA,L]So if HTTPS is off,%1is blank and the protocol ishttp://. If HTTPS is on, then the "s" is grouped and the%1backreference is an "s", thus the protocol ishttps://.However, this is all assuming that port 2368 can handlebothunencrypted and SSL/TLS.ShareFollowansweredOct 15, 2013 at 3:07Jon LinJon Lin143k2929 gold badges221221 silver badges220220 bronze badges12Just a small comment. This is not a redirect, this is resolved by the server acting as a proxy (P flag). To do an actual redirect and ask the client to go to another URL you should use the R flag instead of P.–LudecanDec 14, 2017 at 16:18Add a comment|
I have to redirect port 80 to 2368 in htaccess but I'd like to keep the requested protocol intact so that SSL doesn't break.I currently have this:RewriteCond %{HTTP_HOST} ^sub.domain.com$ [NC] RewriteRule ^ http://sub.domain.com:2368%{REQUEST_URI} [P,QSA,L]which works correctly but I'd like the protocol to be taken from the %{HTTP_HOST} condition if possible.Is there a way to get this to be more dynamic without hard coding domains and protocols?It seems very slow as is.
Preserve HTTP/HTTPS protocol in .htaccess redirects
Try this<IfModule mod_php5.c> php_value short_open_tag 1 </IfModule>This would solve the problemShareFollowansweredSep 23, 2013 at 10:24geekdevgeekdev1,1921111 silver badges1515 bronze badges2Yes, I believe most of the host providers allow to override the php configuration.–geekdevSep 23, 2013 at 10:402Technically, you should be usingphp_flaginstead ofphp_value:secure.php.net/manual/en/configuration.changes.php.–Tyler CromptonDec 4, 2015 at 3:22Add a comment|
I’m currently running through a tutorial for a CMS system which unfortunately uses short open tags.I’ve confirmed that my host will not allow these in their PHP config, but that they run PHP in Apache mode (as opposed to CGI). To the best of my knowledge, this should then allow me to set theshort_open_tagflag toonin an .htaccess file.However, this appears to not be working. In the root directory, I've created an .htaccess file with just the following line, but the short open tags are still being ignored.php_flag short_open_tag onAm I doing something wrong? If not, can anyone suggest why it may not be working? Thanks.Note:Someone has marked this question as being answered somewhere else. Not only does the question identified not have an accepted answer, it's based around and PHP config running in CGI mode, not Apache mode.
Enable PHP short open tags via .htaccess
If you can't edit thephp.inifile itself, you could addset_include_path(get_include_path() . PATH_SEPARATOR . $path_to_add);before yourincludestatements.However if you find yourself havingincludeorrequiretroubles, it is probably a code smell. The best solution would be a good object-oriented design with a good__autoloadfunction.ShareFollowansweredJul 16, 2009 at 3:13OtterfanOtterfan76155 silver badges77 bronze badges3Unfortunately I'm on a server with a lot of other sites right now... I don't want to put the path_to_add in every single file because it's something odd like /home/12345678/public_html... I'd just like to add the "public_html" to the include path in the simplest way possible. Doing a search and replace when the site gets transferred seems clunky.–zildjohn01Jul 16, 2009 at 3:24Could you look up the current phpinclude_pathwithphp_info()orget_include_path()and then add php_value include_path "public/html/root:/first/old/path:/second/old/path" to your.htaccess. You'd only have to do it once.–OtterfanJul 16, 2009 at 3:35True, but I was hoping for a more elegant solution. Hopefully they don't reconfigure the server any time soon. Anyways thanks for the help, this is probably the best it can get.–zildjohn01Jul 16, 2009 at 3:37Add a comment|
Currently on my site I'm using statements like:include 'head.php'; include '../head.php'; include '../../head.php';depending on how many nested folders deep I am. I'm sure there is a better way to do this.I'm convinced.htaccessis the solution, but I'm not sure how to go about implementing it. If I insert:php_value include_path "public/html/root"... I lose the rest of my paths (/usr/lib/php, etc). I naively tried:php_value include_path $include_path . "(path)"but of course this didn't work. How could I prepend or append a single path to this list with.htaccess?
How to append a path to PHP's include_path in .htaccess
Instead of usingmod_rewrite, you can do this with aRedirectMatchdirective:RedirectMatch 404 ^/abc/.*$ShareFollowansweredOct 11, 2011 at 23:45Michał WojciechowskiMichał Wojciechowski2,4901515 silver badges99 bronze badges2RedirectMatch 404 "/abc*" did the job. Thanks for your suggestion.–user977191Oct 12, 2011 at 0:35@Michal Wojciechowski Hi! I used your solution to prevent access to maindomain.com/addon.com. Do you know if it's possible to use it also for preventing access to addon.maindomain.com ? Pls See my questionstackoverflow.com/questions/51268061/…. Thanks–codeispoetryJul 10, 2018 at 14:45Add a comment|
Is there a way to enter a RewriteRule in the htaccess file to redirect to a 404 page if a certain folder/url path as been typed or reached?For example, if I want every user to be redirected to a 404 page if they get to: www.mydomain.com/abc or www.mydomain.com/abc/ or whatever that comes after "abc", even if that folder really exists, I do not want the users to be able to reach it. If they do reach it, I want them to see the 404 error page.*Please note I am not looking to set up a custom 404 error page, I am looking for a way to redirect to the default 404 page.How can I do it? Is it possible?RewriteRule ^abc/(*)?$ [R=404,L]And how can I do the same thing in php, redirect to a 404 error page? Once again I am not talking about setting a custom 404 page, I am talking about the default 404 page, to simply redirect a user to the 404 error page using php.
.htaccess redirect to 404 page RewriteRule
Watch that the directory where your web application is living, is not included in another parent directory which has restrictedFollowSymLinks.The solution is to enableFollowSymLinksat the top directory (parent directory) or move your web application to a directory outside of the scope of the "noFollowSymLinks" in parent directory.For example, the nextapacheconfig could be a problem and surely it reproduces the problem:<VirtualHost *:80> ... <Directory "D:/"> Options Indexes </Directory> <Directory "D:/mywebfolder/"> Options Indexes FollowSymLinks </Directory> ... </VirtualHost>To avoid this problem:<VirtualHost *:80> ... <Directory "D:/"> Options Indexes FollowSymLinks </Directory> ... ... </VirtualHost>Or move yourD:/mywebfolder/to another unit e.g.E:/mywebfolderShareFolloweditedJun 7, 2015 at 19:19Kalle Richter8,2062828 gold badges8686 silver badges187187 bronze badgesansweredJun 19, 2013 at 21:24HokusaiHokusai2,26911 gold badge2121 silver badges2222 bronze badgesAdd a comment|
I've read almost everything possible for this issue and couldn't find anything that would solve my problem. This is erorr log I'm getting: Options FollowSymLinks or SymLinksIfOwnerMatch is off which implies that RewriteRule directive is forbidden: /var/www/vhosts/site.com/httpdocs/cgi-bin/cron.plWhen accessing site I get 403 Forbidden "You do not have permission to access this document." error.I've modified my .htaccess to have this:Options +FollowSymLinks +SymLinksIfOwnerMatch AddDefaultCharset utf-8 RewriteEngine on RewriteCond %{HTTP:Authorization} ^(.*) RewriteRule ^(.*) - [E=HTTP_CGI_AUTHORIZATION:%1] . . .I also added this to httpd.conf:AddHandler cgi-script .cgi AddHandler cgi-script .pl <Directory /> Options -ExecCGI FollowSymLinks -Includes -IncludesNOEXEC -Indexes -MultiViews -SymLinksIfOwnerMatch AllowOverride All </Directory>Really what can I do next?
Options FollowSymLinks or SymLinksIfOwnerMatch is off
According to Wikipedia's page about.htaccess, the name of the language is a combination of the previous answers/comments to this question.Format and language.htaccessfiles are written in theApache Directivesvariant of thePerl Compatible Regular Expressions(PCRE) language. Learning basic PCRE itself can help in mastering work with these files.For historical reasons, the format of.htaccessfiles is a limited subset of theApache HTTP server's global configuration file(httpd.conf) even when used with web servers such asOracle iPlanet Web ServerandZeus Web Serverwhich have very different native global configuration files.Incidentally, "htaccess" is short for"hypertextaccess",and the.dot makes it a hidden file inUnixenviroments.ShareFollowansweredFeb 16, 2019 at 5:16ashleedawgashleedawg20.9k99 gold badges7777 silver badges111111 bronze badgesAdd a comment|
I know some of the syntax and such, but does the whole of writing Redirect Rules and blocked IP addresses have a NAME? Or is it just known as 'Apache .htaccess code'?
What language are apache .htaccess files written in?
Try:RewriteRule ^directory/ - [L,R=404]This redirects all requests for the folder "/directory/", they get a 404 response.ShareFollowansweredSep 11, 2013 at 0:10Jon LinJon Lin143k2929 gold badges221221 silver badges220220 bronze badges6along with this 404 status, can we show the content of a 404.html page?–Tausif AnwarFeb 3, 2017 at 14:16what about PHP and css/html, can they still access the folder?–TheCrazyProfessorNov 2, 2017 at 10:44I get 500 in log instead 404–MrSwedApr 16, 2019 at 10:52do you have mod_rewrite turned on?–Jon LinApr 16, 2019 at 17:16RewriteEngine On RewriteCond %{REQUEST_METHOD} GET RewriteRule ^(.*)$ - [L,R=404] if you want all subdirectories and files inside the folder included with the GET method only.–dhirNov 11, 2022 at 1:46|Show1more comment
I'd like to cut off access to a subdirectory on my site but I want any access in the subdirectory to be a 404 error, not a 403 forbidden. How can this be accomplished?
Send a 404 error via htaccess?
The correct answer isOptions -IndexesYou must have been thinking ofAllowOverride Allhttps://httpd.apache.org/docs/2.2/howto/htaccess.html.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.ShareFolloweditedJul 27, 2018 at 0:01Davy M1,70744 gold badges2121 silver badges2929 bronze badgesansweredOct 5, 2014 at 14:04oasisfleetingoasisfleeting9991212 silver badges66 bronze badges22It'sAllowOverride All–jaggedsoftJan 13, 2016 at 22:182Thanks for pointing that out! I have removed my old answer to this 7 year old question.–Codex73Jan 31, 2017 at 14:53Add a comment|
I have the following .htaccess line, simple no indexes on root.Options -IndexesWhat do we add so it propagates to any sub directory instead of having to create one file for each? One .htaccess on root only.
.htaccess File Options -Indexes on Subdirectories
+50In your HTML you have set a "base" tag:<base href="http://www.cyclistinsuranceaustralia.com.au/">Delete that line from your HTML if you don't need it. This should make the fonts work when viewed fromhttp://cyclistinsuranceaustralia.com.au.You'll probably need to redirecthttp://www.cyclistinsuranceaustralia.com.autohttp://cyclistinsuranceaustralia.com.auShareFollowansweredNov 30, 2014 at 23:19C. LeeC. Lee3,25722 gold badges2323 silver badges2121 bronze badges1I am not using <base tag, even though it gives error–TeekamOct 19, 2016 at 5:55Add a comment|
For some reason fonts have stopped rendering on my sites. The fonts are stored locally, on the same server as the site.I looked up the problem and it seems to be aMissing Cross-Origin Resource Sharing (CORS) Response Headerbut I cannot understand the solution for this.All the various sites say to do is to use:Access-Control-Allow-Origin:*But as I'm primarily front end I do not know where to put it. Is this something my host can help with?What can I do to fix the issue?EDIT:the site in question is:http://cyclistinsuranceaustralia.com.au/The phone number, for example, at the top right should be Bebas font but it is defaulting to Impact.In the console, I get the errors:Font from origin 'http://www.cyclistinsuranceaustralia.com.au' has been blocked from loading by Cross-Origin Resource Sharing policy: The 'Access-Control-Allow-Origin' header has a value 'http://www.cyclistinsuranceaustralia.com.au' that is not equal to the supplied origin. Origin 'http://cyclistinsuranceaustralia.com.au' is therefore not allowed access.I contact my host who said to put:Access-Control-Allow-Origin "http://www.cyclistinsuranceaustralia.com.au"in my .htaccess file but this has no change.
How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?
I voted up the other answers as they were both helpful, but this is what I ended up needing to fix the problem.AddType application/octet-stream .ipa <Files *.ipa> Header set Content-Disposition attachment </Files>ShareFollowansweredSep 20, 2010 at 0:02Greg WGreg W5,21911 gold badge2828 silver badges3333 bronze badges51what about adding .plist support? Do I just add AddType text/xml .plist or do I need the Files elements all over again? Also, which file is all of this added in? Can it go into apache2.conf and apply to everything, or should I put in a virtual host config file?–user798719Mar 18, 2013 at 4:59I have not tested this with .plist files, but I imagine it should work similar to regular xml. I guess it depends on whether you want the file to download or display in the browser.–Greg WMar 18, 2013 at 13:25As for where to put the code, either location (vhost or the global apache .conf file) are fine. If you don't want your configuration to take effect globally, put it in the vhost file.–Greg WMar 18, 2013 at 13:26If you server supports PHP, you may want to take a look atmy php files. They're ready for dealing with this.–cregoxOct 29, 2013 at 14:511This answerhas the info about plists. You have to use a specific URL type in your HTML.–Keith SmileyMar 7, 2014 at 19:41Add a comment|
I'm trying to post .ipa files onto our apache web server for our beta testers to download. Currently I'm using the following line in .htaccess to serve the files:AddType application/octet-stream .ipaThis works great in Safari and Firefox, but in IE the .ipa extension is removed and is instead replaced with .zip. So instead of MyApp.ipa, IE users will get MyApp.zip.I know that I could just zip up all the .ipa's before putting them onto the server and then I wouldn't have to deal with any of this, but I'd like to avoid that extra step if there is a more elegant solution server-side.Or rather, is it possible to simply prevent IE from altering the file extension?
What is the correct mime-type for serving an iPhone .ipa file?
+50RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^.*$ /default.php [L]ShareFolloweditedMay 21, 2011 at 20:10Wander Nauta19.2k11 gold badge4848 silver badges6464 bronze badgesansweredMar 29, 2011 at 8:59user237419user2374198,92744 gold badges3232 silver badges3838 bronze badges0Add a comment|
I must do a little trick for a site! The idea is:if a file for a required url exists then I go to that url, doing nothing more;if a file for a required url not exists, I must go to a file.php and than do something, but NOT changing the url!example:www.mysite.com/page1.htm -> exists -> go to file page1.htmwww.mysite.com/page2.htm -> NOT exists -> go to file default.php but with url "www.mysite.com/page2.htm"It's possible to do this all by .htaccess?
.htaccess url-rewrite if file not exists
\xef\xbb\xbfare three invisible junk characters (at least from Apache's perspective) called the Unicode BOM, or byte order mark. Apache thinks that those characters are part of the command that follows right after. This is what you see in the log, though the characters are escaped so they're visible to the naked eye.\xef\xbb\xbfRewriteEngineIn your editor, especially if your editor is Notepad, make sure you're saving your file without a BOM. This should be selectable in the save as dialog or elsewhere.ShareFollowansweredMar 21, 2011 at 2:55nitro2k01nitro2k017,64744 gold badges2626 silver badges3030 bronze badges22ahhh I see. I used my FTP clients own editor to do the .htaccess, which is probably why this happened. Just did it with notepad and everything is fine now, thanks :)–JoshMar 21, 2011 at 3:002you just saved my life! I couldn't figure out why my rewrite constantly gave a 500 error :) Saved it as Asci and it worked like a charm–DorvallaJul 1, 2015 at 15:37Add a comment|
I am on the shared hostBounceweband I am trying to add some rewrite rules to make my links look prettier.One of these rules is to make the url:http://mysite.com/uploadpoint to:http://mysite.com/upload.php. I have this in my .htaccess file:RewriteEngine on RewriteRule ^upload$ upload.phpbut all it's giving me is a 500 Internal Server Error. I looked at my logs and this comes up a lot:[alert] [client 81.179.29.185] /home/minecraf/public_html/.htaccess: Invalid command '\xef\xbb\xbfRewriteEngine', perhaps misspelled or defined by a module not included in the server configurationDoes this mean my host doesn't support .htaccess? Pretty lame if they don't. I've already tried changing the permissions of .htaccess to 777 and it doesn't help.Thanks!
500 Internal Server Error when using .htaccess with RewriteEngine
UPDATE:As of Apache 2.4,Order,Allow,Deny, andSatisfydirectivesshould not be used anymore. So the new syntax is:AuthType Basic AuthUserFile /www/.site_htpasswd AuthName "Protected Area" <RequireAny> Require ip 1.2.3.4 Require valid-user </RequireAny>ShareFollowansweredFeb 24, 2016 at 10:42fbastienfbastien77111 gold badge99 silver badges2020 bronze badgesAdd a comment|
I have set up a site that is currently work in progress. I'm using an external SMS gateway that needs access to a script on my server. However, I have set up a basic username and password authentication for regular users, but the SMS gateway can't get through that.How can I allow a single IP to pass through the authentication without authenticating itself, and deny all other users that aren't authenticated?Here's my.htaccessfile:Order allow,deny Allow from all AuthType Basic AuthUserFile /www/.site_htpasswd AuthName "Protected Area" require user admin
Allow IP address without authentication
add the following lines to the .htaccess file in the public_html folder:RewriteEngine on RewriteCond %{HTTP_HOST} ^domain-name.com$ [NC,OR] RewriteCond %{HTTP_HOST} ^www.domain-name.com$ RewriteCond %{REQUEST_URI} !folder/ RewriteRule (.*) /folder/$1 [L]ShareFollowansweredNov 14, 2011 at 8:54VilvaVilva8111212 silver badges2323 bronze badges41Could you please explain the purpose of the 'RewriteCond %{HTTP_HOST} ^domain-name.com$ [NC,OR]' and the 'RewriteCond %{HTTP_HOST} ^www.domain-name.com$'? I am using it without those two lines and it seems to be working...–Venkat D.Nov 19, 2012 at 17:30This makes the condition pattern case insensitive, no difference between 'A-Z' and 'a-z'.–VilvaNov 22, 2012 at 18:575Isn't it possible setting the document root in the htaccess file as in the httpd.conf file, with something likeDocumentRoot "c:/inetpub/wwwroot"?–yodabarJan 22, 2013 at 11:391@EmanueleDelGrande I don't believe you can setDocumentRootinside.htaccess, only withinhttpd.conf.–Simon E.Aug 9, 2015 at 0:06Add a comment|
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed12 years ago.Improve this questionMy website has document root ~/public_html but i want to add all the files into ~/public_html/wwwIs there a way to do this with htaccess?Thank you.
Using htaccess to change document root [closed]
Try the first code block you posted, but instead of /index.php try using /(site)/index.php (obv replacing (site) with whatever your site folder is named).ShareFollowansweredMar 1, 2011 at 14:54WNRosenbergWNRosenberg1,87255 gold badges2222 silver badges3131 bronze badges5I just tried it and it didn't work. This is going to turn out to be something stupid I've missed... Thank you for the help.–PaulMar 1, 2011 at 15:01I just moved it to my local server and it works with these .htaccess settings so it must be a server problem.–PaulMar 1, 2011 at 15:092This might sound like a dumb question, but did the server you were originally testing on have mod_rewrite enabled?–WNRosenbergMar 1, 2011 at 15:25I just found why this was not working with my local EasyPHP setup... If you are using an alias for your website, you will need to change "RewriteBase /" to "RewriteBase /alias".–guiwebOct 15, 2014 at 20:32Guys take care of the "RewriteBase"! Put in your subfolder where CodeIgniter is located.–s1xOct 19, 2014 at 18:29Add a comment|
I am having trouble removing index.php from my URLs in Codeigniter. I've made a few websites with Codeigniter 1.7 and the .htaccess code I used doesn't work in 2.I have tried using<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{REQUEST_URI} ^system.* RewriteRule ^(.*)$ /index.php?/$1 [L] RewriteCond %{REQUEST_URI} ^application.* RewriteRule ^(.*)$ /index.php?/$1 [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?/$1 [L] </IfModule>and<IfModule mod_rewrite.c> RewriteEngine on RewriteCond $1 !^(index\.php|images|robots\.txt|css) RewriteRule ^(.*)$ ./index.php/$1 [L] </IfModule>I've also tried it without RewriteBase / in.I have changed the $config['uri_protocol'] to REQUEST_URI and QUERY_STRING and nothing.I have set $config['index_page'] = "";The file structure is 192.168.0.130/(site)/ so it must be going back to the root of the server and can't find the index.php file.All of the controllers I have made can be reached by putting 192.168.0.130/(site)/index.php/testcontrollerThank you.Apologies if this has been asked before - I have looked and tried what I could see.Edit:I should also add that I changed the default folders to beapplicationCI-2.0index.phpand changed the paths in index.php to be correct.
Remove index.php From URL - Codeigniter 2
+50Basically what people try to say is, you can make a rewrite rule like so:RewriteRule ^(.*)$ index.php?params=$1 [NC, QSA]This will make your actual php file like so:index.php?params=param/value/param/valueAnd your actual URL would be like so:http://url.com/params/param/value/param/valueAnd in your PHP file you could access your params by exploding this like so:<?php $params = explode( "/", $_GET['params'] ); for($i = 0; $i < count($params); $i+=2) { echo $params[$i] ." has value: ". $params[$i+1] ."<br />"; } ?>ShareFolloweditedJan 20, 2021 at 16:42answeredOct 30, 2011 at 15:28WesleyWesley2,2001818 silver badges2727 bronze badges3The .htaccess didn't seem to work. I was redirected 404 when I tried to reach localhost/params/param/value.–JohnOct 31, 2011 at 21:00What happens when you only try to put localhost/params ?–WesleyOct 31, 2011 at 21:395This is old, but for future reference, I tested this and it DIDN'T WORK (paramsgave me'index.php'). I solved it by adding theQSA flag, so, instead of just[NC], I have[NC,QSA]. Also, it looked like this:index.php?params=params/param/value/param/value, so it would be ok to removeparamsand just keep it like so:http://url.com/param/value/param/value.–FirstOneJan 14, 2016 at 22:07Add a comment|
I have a index.php which handle all the routing index.php?page=controller (simplified) just to split up the logic with the view.Options +FollowSymlinks RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([\w\d~%.:_\-]+)$ index.php?page=$1 [NC]Which basically:http://localhost/index.php?page=controllerTohttp://localhost/controller/Can anyone help me add the Rewrite forhttp://localhost/controller/param/value/param/value(And soforth)That would be:http://localhost/controller/?param=value&param=valueI can't get it to work with the Rewriterule.A controller could look like this:<?php if (isset($_GET['action'])) { if ($_GET['action'] == 'delete') { do_Delete_stuff_here(); } } ?>And also:<?php if (isset($_GET['action']) && isset($_GET['x'])) { if ($_GET['action'] == 'delete') { do_Delete_stuff_here(); } } ?>
.htaccess rewrite GET variables
According tothis articleyou can accomplish this by usingSetEnvIf. You match each of the folders and files you want to grand access to and define an environment variable 'allow' for them. Then you add a condition that allows access if this environment variable is present.You need to add the following directives to your .htaccess.SetEnvIf Request_URI "(path/to/directory/)$" allow SetEnvIf Request_URI "(path/to/file\.php)$" allow Order allow,deny Allow from env=allow Satisfy anyShareFolloweditedAug 24, 2014 at 9:14Sumurai820.5k1111 gold badges6767 silver badges101101 bronze badgesansweredJan 2, 2012 at 6:04Sudhir BastakotiSudhir Bastakoti99.7k1515 gold badges160160 silver badges166166 bronze badges2@SherwinFlight I follow above code but still asking password, how to exclude directory for upload images–NullpointerFeb 17, 2016 at 7:08The paths on the URI don't need the parenthesis and should be anchored to the start (^) instead of the end ($). This can also be done without using an environment variable by usingrequire.–meldsJul 27, 2022 at 18:08Add a comment|
I have a directory protected by htaccess. Here is the code I use now:AuthName "Test Area" Require valid-user AuthUserFile "/***/.htpasswd" AuthType basicThis is working fine. However, I now have a directory inside of this folder that I would like to allow anyone to access, but am not sure how to do it.I know that it is possible to just move the files outside of the protected directory, but to make a long story short the folder needs to stay inside the protected folder, but be accessible to all.How can I restrict access to the folder, but allow access to the subfolder?
Exclude one folder in htaccess protected directory
RewriteCond %{REQUEST_URI} foobar RewriteRule .* index.phporsome variant thereof.ShareFollowansweredJul 10, 2010 at 18:30Ignacio Vazquez-AbramsIgnacio Vazquez-Abrams786k155155 gold badges1.4k1.4k silver badges1.4k1.4k bronze badges11Thanks for your quick response. Works perfectly but just realised instead of rewrite I need it to redirect. Is this possible?–LeeJul 10, 2010 at 18:35Add a comment|
How would I write a.htaccessredirect rule if the URL contains a certain word?e.g. if it containsfoobarthen redirect toindex.php
htaccess redirect if URL contains a certain string
This should do it:RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} !new-example.com$ [NC] RewriteRule ^(.*)$ http://new-example.com/$1 [L,R=301]ShareFolloweditedJan 16, 2014 at 20:28answeredDec 9, 2011 at 19:24Eric BrandelEric Brandel87077 silver badges99 bronze badges5My .htaccess file already has this code (Wordpress) in it: <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> do I need those 4 lines of code you gave me? Or will I have a problem putting in RewriteEngine On twice (same for RewriteBase /)–jasonaburtonDec 9, 2011 at 19:27skip the first two lines if they already exist in your .htaccess–Ulrich PalhaDec 9, 2011 at 19:31These redirects are not working. The only code I have in my .htaccess is posted in my comment above. Is there a reason its not working?–jasonaburtonDec 9, 2011 at 19:49I even took out all the code in my .htaccess file and just put your code in and it still doesn't work.–jasonaburtonDec 9, 2011 at 19:54note that than you change to your real domain namenew-example.comboth times, old one don't take part–HebeApr 18, 2022 at 19:05Add a comment|
I am redirecting one domain to another, but I want to preserve the path in the redirect. So for example, I want to visitwww.example.com/services/education/page.html, but my redirect will bring them towww.new-example.com/services/education/page.html. What do I write in my .htaccess file to preserve the path "/services/education/page.html"?Right now I have:redirect 301 http://www.example.com/ http://www.new-example.com/But I'm not sure if that works or not (Can't test yet as I am waiting for domain details etc). I just want to be sure when I put the site live. Is that right or am I way off base?Thanks!
How to 301 redirect an entire domain while preserving the path
I get around it this way. Just allow Non-SSL since it will be redirected then require auth once on SSL...SetEnvIf %{SERVER_PORT} ^80$ IS_NON_SSL RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} AuthUserFile /etc/hi AuthName "hi" AuthType Basic require valid-user Allow from env=IS_NON_SSLShareFollowansweredApr 11, 2013 at 3:46BenBen24244 silver badges33 bronze badges43Elegant solution to a not entirely obvious problem. I ended up usingAllow from env=!HTTPSwhere HTTPS is set on SSL requests, but the same concept applies. Thanks.–Chris HealdMay 25, 2013 at 7:042SERVER_PORT is not an option available in SetEnvIf directive as per the documentation athttpd.apache.org/docs/2.2/mod/mod_setenvif.html#setenvif–Alagappan RamuMar 20, 2014 at 19:184Plus at least in my case it stills asks for authentication twice.–LWCMar 22, 2016 at 20:55@ChrisHeald could you post your solution as an answer? Because this one here does not work for me.–AdamApr 18, 2017 at 13:41Add a comment|
This is my .htaccess:RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} AuthUserFile /etc/hi AuthName "hi" AuthType Basic require valid-userIt asks for user authentication using http, meaning that password will be sent in plain text. It will than redirect to the https version and ask the password again.How can i fix it?
Apache .htaccess redirect to HTTPS before asking for user authentication
I've found an somewhat elegant way to do it:.user.ini filesIt seems to be the .htaccess version for PHP-FPM.ShareFollowansweredFeb 8, 2016 at 21:48Mario HaubenwallnerMario Haubenwallner1,89511 gold badge1919 silver badges2222 bronze badges31Basically, this is the best option to control several PHP ini directives. However, many of those can't be controlled via .user.ini files. See thelist of directives: all those tagged with PHP_INI_SYSTEM require different approach as given in other answers. And though you could set those via global php.ini using approaches via environment variables enables to have fine-grained control over those options depending on current virtual host, request method, request URL etc.–Thomas UrbanDec 16, 2018 at 10:11This doesn't seem to work recursively like .htaccess does for folders and files underneath the folder where the .htaccess is located. At least not when there is no php file located at the folder level.–Tommy BravoApr 1, 2020 at 20:291That's right. The .user.ini is part of php-fpm, unlike .htaccess that is part of apache. When no php file is requested, php-fpm would not be called.–immeJul 6, 2020 at 16:32Add a comment|
under Apache + PHP asmoduleyou can setphp_value post_max_size 8Minside a .htaccess.How can I do this under Apache + PHP-FPM?I'm using the FastCgiExternalServer directive, but want to keep the functionality within the .htaccess file (if possible).Thank you!
Equivalent of php_value under Apache + php-fpm
Try changing your first three lines to:RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R=301,L]Ibelieve, that unless you attempted to go tohttps://en.example.com/:443then {SERVER_PORT} will never return 443.ShareFolloweditedApr 7, 2015 at 4:30answeredApr 6, 2015 at 20:16eat-sleep-codeeat-sleep-code4,7851414 gold badges5353 silver badges9898 bronze badges7Is there a publicly-accessible URL to view your site's behavior?–eat-sleep-codeApr 6, 2015 at 20:29Oh there is still a problem: Currently I´m also able to open the URL with http only.–mm1975Apr 7, 2015 at 13:11So, it isn't forwarding you to https?–eat-sleep-codeApr 7, 2015 at 15:04sorry for the late response. Now it works! I think, it was a server cache issue.–mm1975Apr 11, 2015 at 8:201What if I get theERR_TOO_MANY_REDIRECTSerror? How do I fix that?–PathrosMar 21, 2016 at 16:18|Show2more comments
with my WordPress-Blog, I switch to https. Therefore, I have add the following code to my .htaccess-File. My Problem now is, that I get the issue "Too many Redirects". Thank you for your tips!Domain is a Subdomain:https://en.example.com# Begin Force SSL RewriteEngine On RewriteCond %{SERVER_PORT} !^443$ RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L] # End Force SSL # 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
Too many Redirects after switching WordPress to https
Place this code in/My-Project/.htaccess:RewriteEngine On RewriteBase /My-Project/ RewriteCond %{THE_REQUEST} /public/([^\s?]*) [NC] RewriteRule ^ %1 [L,NE,R=302] RewriteRule ^((?!public/).*)$ public/$1 [L,NC]ShareFollowansweredMay 13, 2014 at 17:46anubhavaanubhava771k6666 gold badges582582 silver badges649649 bronze badges5This is partially working, everything loads except images which are returning 404's. this is because I'm usingretina images for PHP, which has me create a.htaccessin the/public/dir, it redirects image requests to retina-equivalents. Is there a way to make these two methods play nice together?–tdcMay 13, 2014 at 18:051It can be done, can you post your .htaccess from/My-Project/public/.htaccess?–anubhavaMay 13, 2014 at 18:211@pathros: It is working and tested solution. You can post a new question with all the details to get your problem resolved.–anubhavaJul 22, 2016 at 15:58I getRequest exceeded the limit of 10 internal redirects due to probable configuration error.Thisworked for me.–Jean-Marc ZimmerNov 3, 2018 at 11:472Note: If you're using XAMPP or similar, your/htdocs/my-project/.htaccessfile should useRewriteBase /my-project/too!–Jimmy AdaroMay 27, 2019 at 18:31Add a comment|
Bellow is my site directory structure:htdocs/ My-Project/ public/ index.php css/ img/ js/ src/ config.php templates/ library/I do not want any direct user access to any files inside thesrcdirectory.srccontains my templating and backend logic scripts.I want to set up my.htaccessso that when the user goes to my website (root folderMy-Project), they are redirected toMy-Project/public/index.php. I would like the URL to simply look likeMy-Project.comwhile on the index page.Any help? I am hesitant to modify my .htaccess file as I see a lot of conflicting advice around here and on the net as to the best way to do this.
.htaccess redirect from site root to public folder, hiding "public" in URL?
+150RewriteCond %{REQUEST_URI} !^/(csNewsAd|csNewsAd/.*)$instead ofRewriteRule ^/csNewsAd($|/) - [L]ShareFolloweditedOct 7, 2016 at 17:11David3,16622 gold badges3131 silver badges5151 bronze badgesansweredFeb 28, 2010 at 6:29GmonCGmonC10.9k11 gold badge3030 silver badges3838 bronze badges6Didn't work either. Which is odd, because thisshouldwork already. I'm starting to hate Wordpress, might as well try to configure a subdomain to access this folder and get rid of the problem.–Joel A. Villarreal BertoldiFeb 28, 2010 at 19:44Although it didn't work, I'm gonna take this one as as accepted answer, as it is the most complete one.–Joel A. Villarreal BertoldiFeb 28, 2010 at 20:21I would try Wordpress official forums. I've had some strange problems in the past in this CMS and they solved. If it's not working, try to insert some garbage in your .htaccess and see if it's really working, maybe it's another problem with your installation. Good luck!–GmonCFeb 28, 2010 at 20:27+1 Good job. I ended looking at WP MU for a few hours before coming back and realizing I still wanted to do this.–phyattJul 20, 2013 at 6:381Please update the Source link. It leads to a German page unrelated to the question.–MSDApr 16, 2015 at 23:05|Show1more comment
I have this .htaccess file in WordPress. It's located at /public_html/ (web root). I need to exclude a folder (csNewsAd) from the rewrite engine. I've tried this, based from another question similar here at SO, but didn't work at all.AddHandler x-httpd-php5 .php # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^/csNewsAd($|/) - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPressAny suggestions?More dataThere's another .htaccess inside /csNewsAd for password protection:AuthName "Clasificados" AuthType "basic" AuthUserFile /home/ig000192/public_html/csNewsAd/.passwd Require valid-user
.htaccess & WordPress: Exclude folder from RewriteRule